当前位置: 移动技术网 > IT编程>移动开发>Android > Android开发之引用外部数据库操作讲解

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

2018年09月14日  | 移动技术网IT编程  | 我要评论

lcr电桥,toshi小弟吧,如何搭配服装

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 等。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网