【问题标题】:how to connect to sqlite database in android studio? [duplicate]如何连接到 android studio 中的 sqlite 数据库? [复制]
【发布时间】:2015-12-27 09:41:30
【问题描述】:

我使用 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();

【问题讨论】:

    标签: android sqlite android-studio


    【解决方案1】:

    您可以使用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);
    

    【讨论】:

      猜你喜欢
      • 2015-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-24
      • 1970-01-01
      相关资源
      最近更新 更多