有現(xiàn)成的數(shù)據(jù)庫油湖,需要直接引入到項目中使用。
#準(zhǔn)備
在開始之前我們要確認(rèn)現(xiàn)有的數(shù)據(jù)庫的表結(jié)構(gòu)和字段信息等领跛。(注意要看清楚數(shù)據(jù)庫的大小乏德,后面有用)
#第一步
將外部數(shù)據(jù)庫拷貝到項目中的 assets文件夾中,如圖
#第二步
在你要使用數(shù)據(jù)庫之前將數(shù)據(jù)庫拷貝到 /data/data/包名/databases/ 目錄下。
通過獲取數(shù)據(jù)庫的大小判斷一下是否已經(jīng)拷貝完成喊括。
代碼
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目錄下復(fù)制
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");
}
到這里已經(jīng)成功的把外部數(shù)據(jù)庫拷貝到項目中胧瓜,并且開始 CRUD 了。
以上的方法郑什,是做簡單也是最原始的方法府喳,之后會嘗試使用第三方的工具來查詢,如 GreenDao LitePal 等蘑拯。
在Android開發(fā)中使用數(shù)據(jù)庫進(jìn)行存儲查詢等操作是基本功钝满,推薦可以看看以下文章:
- 郭神的LitePal 系列文章 Android數(shù)據(jù)庫高手秘籍
- Android 數(shù)據(jù)庫對比 傳送門
查看數(shù)據(jù)庫的工具:Sqlitebrowser
下載地址