2012-07-13 66 views
0

我有一個數據庫,我想在我的應用程序的下一次更新時更改該數據庫..但我不想丟失數據庫中的當前數據(在應用程序目錄中)..我必須複製在新的數據庫中的數據並刪除舊database..How我能做到這一點?有沒有關於任何其他的想法讓我知道...提前升級應用程序更新數據庫

感謝..

這是我當前的數據庫代碼...

public class DbUtils { 
public static String DB_PATH; 
private String DB_NAME; 
File dbDir; 
private SQLiteDatabase dataBase; 
public DbUtils(File fileDirectory, String sqliteFileName) { 

    this.DB_NAME = sqliteFileName; 
    dbDir = fileDirectory; 
} 

public void createDatabaseIfNotExists(Context context) throws IOException { 
    boolean createDb = false; 

    File dbFile = new File(dbDir.getAbsolutePath() + "/" + DB_NAME); 
    DB_PATH = dbFile.getAbsolutePath(); 

    if (!dbDir.exists()) { 
     dbDir.mkdir(); 
     createDb = true; 
    } else if (!dbFile.exists()) { 
     createDb = true; 
    } else { 
     boolean doUpgrade = false; 

     if (doUpgrade) { 
      dbFile.delete(); 
      createDb = true; 
     } 
    } 

    if (createDb) { 
     InputStream myInput = context.getAssets().open(DB_NAME); 
     OutputStream myOutput = new FileOutputStream(dbFile); 
     byte[] buffer = new byte[1024]; 
     int length; 
     while ((length = myInput.read(buffer)) > 0) { 
      myOutput.write(buffer, 0, length); 
     } 

     myOutput.flush(); 
     myOutput.close(); 
     myInput.close(); 
    } 
} 

public SQLiteDatabase getStaticDb() { 
    return dataBase = SQLiteDatabase.openDatabase(DB_PATH, null, 
      SQLiteDatabase.OPEN_READWRITE); 
} 

public void closeDataBase(){ 
    if(dataBase!=null && dataBase.isOpen()){ 
     dataBase.close(); 
    } 
} 

} 
+0

當你說:「在下次更新時更改數據庫,」你的意思是表架構的變化?我只是想了解爲什麼要刪除當前數據庫。 – 2012-07-13 20:05:24

回答

0

更常見的解決方案是保持數據庫,b ut儘可能多地轉換它以使用新版本的應用程序。這被稱爲「數據庫升級」。

您可能會擔心,如果此過程在升級過程中失敗,則您既沒有舊數據庫也沒有新數據庫。這可以通過數據庫事務來解決。如果整個數據庫升級過程發生在單個事務中,那麼該事務將失敗並且什麼都不做,這樣您就可以繼續使用舊版本的應用程序,或者成功,並且可以使用新版本的應用程序。

這是如何包裝你的數據庫升級的交易:

SQLiteDatabase database = SQLiteDatabase.openDatabase(uri, null, SQLiteDatabase.SQLITE_OPEN_READWRITE); 
database.beginTransaction(); 

// put your database upgrade code here, for example: 
database.execSQL("ALTER TABLE MyTable ADD NewColumn int"); 
database.execSQL("ALTER TABLE AnotherTable ADD AnotherColumn int"); 

database.endTransaction(); 
database.setTransactionSuccessful(); 
相關問題