频道栏目
首页 > 资讯 > Android > 正文

Android开发之引用外部数据库操作讲解

18-07-30        来源:[db:作者]  
收藏   我要投稿

Android 引用外部数据库(一)

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

#准备

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

#第一步

将外部数据库拷贝到项目中的 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 等。

相关TAG标签
上一篇:Eclipse报错显示Unable to build: the file dx.jar was not loaded from the SDK folder的解决办法
下一篇:关于使用HttpClient访问https安全链接,双向认证核心部分实例讲解
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站