我使用sql浏览器创建了一个sqlite数据库(mydb.db),然后在android应用程序中创建了Assets文件夹并mydb.db
在上面添加了文件。
如何连接到该数据库?我使用此代码,但无法正常工作。
SQLiteDatabase db;
db = openOrCreateDatabase("DataBase.db",
SQLiteDatabase.CREATE_IF_NECESSARY, null);
Cursor c = db.rawQuery("SELECT * FROM user", null);
c.moveToFirst();
while(!c.isAfterLast()) {
Toast.makeText(this, c.getString(0) + " " + c.getString(1), Toast.LENGTH_SHORT).show();
c.moveToNext();
}
db.close();
您可以使用SQLiteAssetHelper,它具有在您的应用程序首次运行时安装预打包数据库所需的所有代码。
您无法直接从资产文件夹中打开文件。您必须将资产文件夹的数据库文件复制到内部/外部存储中,然后使用“文件”路径打开文件。
快速查看代码示例以复制数据库:
private void copydatabase() throws IOException {
//Open your local db as the input stream
InputStream myinput = mycontext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outfilename = DB_PATH + DB_NAME;
//Open the empty db as the output stream
OutputStream myoutput = new FileOutputStream("/data/data/(packagename)/databases /(datbasename).sqlite");
// transfer byte to inputfile to outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myinput.read(buffer))>0) {
myoutput.write(buffer,0,length);
}
//Close the streams
myoutput.flush();
myoutput.close();
myinput.close();
}
现在您可以像这样使用数据库:
String mypath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(mypath, null, SQLiteDatabase.OPEN_READWRITE);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句