2015-12-27 101 views
0

我使用sql瀏覽器創建了一個sqlite數據庫(mydb.db) 然後我在android應用程序中創建了資產文件夾並在其上添加了mydb.db文件。如何連接到android studio中的sqlite數據庫?

如何連接到這個數據庫? 我使用此代碼,但它無法正常工作。

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(); 

回答

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);