android:sqlite的使用(读取res/raw的db文件)一种方法

2017-01-07 11:12:23来源:作者:人点击

1、

public static final String		DATABASE_FILENAME	= "stock.db";				// 这个是DB文件名字	public static final String		PACKAGE_NAME		= "com.huaxa.it.tuling";	// 这个是自己项目包路径	public static final String		DATABASE_PATH		= android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/"																 +PACKAGE_NAME;	// 获取存储位置地址

2、将res/raw的db文件读取出来,然后在手机某个目录下并生成db文件

private SQLiteOpenHelper		sqlHelper;	private static SQLiteDatabase	database;	private String					name				= "";						// 股票搜索出来的代码	static String databaseFilename = DATABASE_PATH + "/" + DATABASE_FILENAME;	public static SQLiteDatabase openDatabase(Context context)	{		try		{//			String databaseFilename = DATABASE_PATH + "/" + DATABASE_FILENAME;			File dir = new File(DATABASE_PATH);			if (!dir.exists())			{				dir.mkdir();//新建文件			}			if (!(new File(databaseFilename)).exists())			{				InputStream is = context.getResources().openRawResource(						R.raw.stock);				FileOutputStream fos = new FileOutputStream(databaseFilename);				byte[] buffer = new byte[8192];				int count = 0;				while ((count = is.read(buffer)) > 0)				{					fos.write(buffer, 0, count);				}				fos.close();				is.close();			} 			database = SQLiteDatabase.openOrCreateDatabase(databaseFilename,					null);			return database;		} catch (Exception e)		{			e.printStackTrace();		}		return null;	}
3、操作数据库
// 获取股票代码	public void getGuPiaoDaiMA(String str)	{		SQLiteDatabase db = openDatabase(this); 		Cursor c = db.rawQuery("select * from db where name=?" ,new String[]{"南方航空"});//此处的db是表名,name是列名  		c.moveToFirst(); 		while (!c.isAfterLast())		{			name = c.getString(c.getColumnIndex("代码")); 			c.moveToNext();		}	}


最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台