Android wiki : 20.操作自各儿已有的数据库

Android wiki : 20.操作自己已有的数据库
//打开一个已有的数据库
SQLiteDatabase db = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);

例子:操作手机归属地的数据库

1:将自己的数据库放到项目的assets/下
	assets/address.db
	
2:软件启动时将数据库复制到data/data/包名/files/目录下(因为应用访问不了assets这个资产目录)
	/**
	 * 将assets目录下的数据库address.db复制到data/data/包名/files/address.db
	 */
	private void copyDB() {

		File file = new File(getFilesDir(), "address.db");

		if (file.exists() && file.length() > 0) {
			Log.i(TAG, "address.db已经存在,需要复制");
		} else {
			InputStream is = null;
			OutputStream os = null;
			try {
				is = getAssets().open("address.db");
				os = new FileOutputStream(file);
				byte[] bu = new byte[1024];
				int len = 0;
				while ((len = is.read(bu)) != -1) {
					os.write(bu, 0, len);
				}

				Log.i(TAG, "复制数据库完成");
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
						is.close();
						os.close();
				}
			}

		}
	}

3:操作数据库

private static String path = "data/data/com.zhong.mobilephonetools/files/address.db";
public static String queryNumber(String number) {
	SQLiteDatabase db = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
	String location = number;
	String sql = "select location from data2 where id=(select outKey from data1 where id=?)";
	Cursor cursor = db.rawQuery(sql, new String[] { number.substring(0, 7) });
	while (cursor.moveToNext()) {
		location = cursor.getString(0);
	}
	return location;
}
	
	


版权声明:本文为博主原创文章,未经博主允许不得转载。