私のアプリケーションを作成すると、私のデータベースはassetsフォルダから私のアプリケーションにコピーされます。Asstsフォルダからデータベースをアップグレードする
私はonUpgradeをやりたければ、ただ1つを除いてすべてのテーブルを上書きしたいだけです。
しかし、どうすればいいですか? 私はちょうど全体のデータベースを書くことができますか何も...
私を助けてください。
もちろんこのdoesntの仕事は、それが既存のテーブルを上書きdoesntのため、それはちょうど私が代わりにはなりませんものをバックアップ..
public void createDataBase() throws IOException{
boolean dbExist = checkDataBase();
if(dbExist){
myDataBase = this.getWritableDatabase();
} else {
myDataBase = this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
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(outFileName);
//transfer bytes from the inputfile to the 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();
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.i("onUpgrade", "newVersion: "+newVersion+", oldVersion: "+oldVersion);
try{
if(newVersion > oldVersion){
db.execSQL("ALTER TABLE Results RENAME TO temp_Results");
db.execSQL("CREATE TABLE Results (lektionenId INTEGER PRIMARY KEY, testPassed Integer, lektionPassed Integer)");
db.execSQL("INSERT INTO Results (testPassed, lektionPassed) SELECT testPassed, lektionPassed FROM temp_Results");
db.execSQL("DROP TABLE IF EXISTS temp_Results");
}
} catch(Exception e){
Log.i("exc", ""+e);
}
}
EDIT:
私はデータベースを呼び出します。
myDbHelper = new LernAppOpenHelper(this, "LernApp", DbConfig.DB_VERSION_LERNAPP);
try {
String[] columns = {"_id","description"};
myDbHelper.createDataBase();
myDbHelper.openDataBase();
cursor = myDbHelper.getQuery("Uebersicht", columns, null, null, null, null, null);
そして、私のONUPGRADE方法:
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if(newVersion > oldVersion){
if("LernApp".equals(DATABASE_NAME)){
myContext.deleteDatabase(DATABASE_NAME);
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
}
これは良い答えです!ありがとうございます:) – krackmoe
しかし、どの形式でステップ1をやりますか?すべてのテーブルをTextFileとして保存してください!またはこれはどのように良いと思いますか? – krackmoe
@krackmoe:更新された回答を参照してください。 – CommonsWare