android 外部引用,Android 引用外部数据库(一)

有现成的数据库,需要直接引入到项目中使用。

#准备

在开始之前我们要确认现有的数据库的表结构和字段信息等。(注意要看清楚数据库的大小,后面有用)

#第一步

将外部数据库拷贝到项目中的 assets文件夹中,如图

904508f3a937

#第二步

在你要使用数据库之前将数据库拷贝到 /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 等。

在Android开发中使用数据库进行存储查询等操作是基本功,推荐可以看看以下文章:

郭神的LitePal 系列文章 Android数据库高手秘籍

Android 数据库对比 传送门

查看数据库的工具:Sqlitebrowser

下载地址

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值