有現成的數據庫,需要直接引入到項目中使用。
在開始之前我們要確認現有的數據庫的表結構和字段信息等。(注意要看清楚數據庫的大小,后面有用)
將外部數據庫拷貝到項目中的 assets文件夾中,如圖
在你要使用數據庫之前將數據庫拷貝到 /data/data/包名/databases/ 目錄下。
public static void copyDbFile(Context context, String db_name) { InputStream in = null; FileOutputStream out = null; //String path = "/data/data/" + context.getPackageName() + "/databases/"; File filePath = context.getDatabasePath(db_name); //spUtils 是為了防止多次拷貝 if (!SharePreferenceUtils.getBoolean(GlobalContent.COPE_SUCCESS,false)){ try { in = context.getAssets().open(db_name); // 從assets目錄下復制 out = new FileOutputStream(filePath); int length = -1; byte[] buf = new byte[1024]; while ((length = in.read(buf)) != -1) { out.write(buf, 0, length); } out.flush(); SharePreferenceUtils.putBoolean(GlobalContent.COPE_SUCCESS,true); } catch (Exception e) { e.printStackTrace(); } finally { try { if (in != null) in.close(); if (out != null) out.close(); } catch (IOException e1) { e1.printStackTrace(); } } } }
這時就可以開始查庫了
SqlLiteHelper sqlLiteHelper = new SqlLiteHelper(getContext(), "mySql.db", null, 1); SQLiteDatabase readableDatabase = sqlLiteHelper.getReadableDatabase(); try { Cursor query = readableDatabase.query("message", new String[]{"_id", "message"}, null, null, null, null, null, limit); boolean b = query.moveToFirst(); while (!query.isLast()) { int id = query.getInt(query.getColumnIndex("_id")); String message = query.getString(query.getColumnIndex("message")); mDataList.add(new LoveMessageBean(id, message)); query.moveToNext(); } query.close(); Logger.i("mDataList : "+ mDataList.size()); }catch (Exception e){ UiUtils.showToast(getContext(),"error"); }
到這里已經成功的把外部數據庫拷貝到項目中,并且開始 CRUD 了。
以上的方法,是做簡單也是最原始的方法,之后會嘗試使用第三方的工具來查詢,如 GreenDao LitePal 等。