Android 数据库从助理文件夹升级
创建我的应用程序时,我的数据库将从资产文件夹复制到我的应用程序 现在,如果我想做一个onUpgrade,我只想覆盖除一个表之外的所有表 但是我该怎么做呢? 我只能写整个数据库或者什么都不写 请帮我做这个 当然,这不起作用,因为它不会覆盖现有的表,它只是备份我不替换的表Android 数据库从助理文件夹升级,android,Android,创建我的应用程序时,我的数据库将从资产文件夹复制到我的应用程序 现在,如果我想做一个onUpgrade,我只想覆盖除一个表之外的所有表 但是我该怎么做呢? 我只能写整个数据库或者什么都不写 请帮我做这个 当然,这不起作用,因为它不会覆盖现有的表,它只是备份我不替换的表 public void createDataBase() throws IOException{ boolean dbExist = checkDataBase(); if(dbExist){
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");
}
}
}
}
步骤1:将表数据从旧数据库复制到内存中
步骤2:从复制资产中恢复数据库
步骤3:从内存中的表数据更新新数据库
如果表可能太大,则将数据复制到文件中,然后从文件中返回
编辑 或: 步骤1:使用标准Java文件I/O将旧数据库(被替换的数据库)复制到新数据库 步骤2:从复制资产中恢复数据库 步骤3:打开两个数据库 第4步:从旧数据库加载保留的表,并将其内容注入新数据库。一定要注意事务:默认情况下,每条语句一个事务可能会使这类工作非常缓慢
步骤#5:完成后,关闭旧数据库并将其删除。但您将以何种格式执行步骤1?将每个表另存为文本文件!?或者你认为这会有什么好处?顺便问一句,你觉得这个怎么样:1。将表转储到内存2中。删除旧数据库3。创建新数据库4。将转储文件插入新数据库应该有效吗?@krackmoe:只要内存表不是旧数据库的一部分(例如,您使用的是不同的
SQLiteDatabase
对象),理论上应该有效。好的,我管理了它。但我有一个新问题。。。将删除数据库并插入新数据库。但是如果我在第一次显示新数据时打开应用程序,如果我在第二次显示新数据时打开应用程序。。我不明白为什么。。如果你能再次帮助我,我将不胜感激。我在上面编辑了我的帖子,并添加了必要的代码。。。