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

来源:互联网 发布:淘宝10元包邮在哪 编辑:程序博客网 时间:2024/06/04 17:47
//打开一个已有的数据库SQLiteDatabase db = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);例子:操作手机归属地的数据库1:将自己的数据库放到项目的assets/下assets/address.db2:软件启动时将数据库复制到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;}


0 0