2015-03-25 35 views
1

我正在運輸數據庫文件與我們的Android應用程序。爲此我跟着How to ship an Android application with a database?回答了Danny Remington - OMS更新SQLite數據庫時,應用程序與數據庫一起發佈的新版本

現在我必須提供新版本,該數據庫架構發生了變化,所以首先我從資產數據/數據目錄複製新的數據庫文件,寫一個INSERT語句作爲SqliteOpenHelper類的onUpgrade方法如下:

//rename the old database 
new File(DB_PATH + DATABASE_NAME).renameTo(new File(DB_PATH + "DB_old")); 
    try 
    { 
     //copting new db file from assets to data/data dir 
     copyDataBase(); 
    } 
    catch (IOException e) 
    { 
     e.printStackTrace(); 
    }      
    SQLiteDatabase DB_old = SQLiteDatabase.openDatabase(DB_PATH + "DB_old", null, SQLiteDatabase.OPEN_READWRITE); 
    SQLiteDatabase DB_new = SQLiteDatabase.openDatabase(DB_PATH + "DB_new", null, SQLiteDatabase.OPEN_READWRITE); 
    //insert statement from old to new db 
    String query = "INSERT INTO DB_new.table1(user_id,user_name) SELECT * FROM DB_old.table1"; 

    DB_new.execSQL(query); 
    DB_old.close(); 
    DB_new.close(); 
    //deleting old db file 
    new File(DB_PATH + "DB_old").delete(); 

但插入語句拋出一個異常android.database.sqlite.SQLiteException: no such table: DB_new.table1

我如何能實現this.Please幫助我在此。

回答

1

在你的sqlite幫手中,有一個方法onUpgrade,當你傳遞給超級構造函數(SqliteOpenHelper)的版本發生變化時會觸發該方法。因此,您需要更改此號碼,以便onUpgrade激發,然後將您的代碼用於在該方法中「重新安裝」數據庫。