1
创建我的应用程序时,我的数据库从assets文件夹复制到我的应用程序。从Assts文件夹升级数据库
现在,如果我想要做一个onUpgrade,我只想覆盖所有的表格,除了一个。
但我该怎么做? 我只是可以写整个数据库或什么也没有...
请帮我这个。
这当然行不通的,因为它不覆盖现有的表,它只是备份一个我不更换..
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);
}
}
编辑:
如果我调用数据库:
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