有現(xiàn)成的數(shù)據(jù)庫(kù),需要直接引入到項(xiàng)目中使用。
#準(zhǔn)備
在開(kāi)始之前我們要確認(rèn)現(xiàn)有的數(shù)據(jù)庫(kù)的表結(jié)構(gòu)和字段信息等。(注意要看清楚數(shù)據(jù)庫(kù)的大小,后面有用)
#第一步
將外部數(shù)據(jù)庫(kù)拷貝到項(xiàng)目中的 assets文件夾中,如圖

#第二步
在你要使用數(shù)據(jù)庫(kù)之前將數(shù)據(jù)庫(kù)拷貝到 /data/data/包名/databases/ 目錄下。
通過(guò)獲取數(shù)據(jù)庫(kù)的大小判斷一下是否已經(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();
}
}
}
}
#第三步
這時(shí)就可以開(kāi)始查庫(kù)了
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ù)庫(kù)拷貝到項(xiàng)目中,并且開(kāi)始 CRUD 了。
以上的方法,是做簡(jiǎn)單也是最原始的方法,之后會(huì)嘗試使用第三方的工具來(lái)查詢,如 GreenDao LitePal 等。
在Android開(kāi)發(fā)中使用數(shù)據(jù)庫(kù)進(jìn)行存儲(chǔ)查詢等操作是基本功,推薦可以看看以下文章:
- 郭神的LitePal 系列文章 Android數(shù)據(jù)庫(kù)高手秘籍
- Android 數(shù)據(jù)庫(kù)對(duì)比 傳送門(mén)
查看數(shù)據(jù)庫(kù)的工具:Sqlitebrowser
下載地址