【发布时间】:2015-03-09 11:20:42
【问题描述】:
我已经进行了一些搜索并阅读了许多帖子,但在不丢失已保存数据的情况下尝试更新数据库仍然没有成功。
我使用本教程创建了数据库:http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/
在新数据库中,我想将数据从主表迁移到将存储用户收藏夹的新表。目前,它们存储在主表中。在 onupgrade 函数中,我尝试重命名表并将记录插入到新表中。那没有用。我还尝试将数据保存到游标,然后填充新表,但这没有用。对于这些方法,我收到错误说找不到新/旧表。
下面是 onUpgrade() 函数。
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (newVersion > oldVersion) {
db.execSQL("ALTER TABLE books rename to old_books");
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
db.execSQL("INSERT into favourites (_id, type, title, notes,rating) SELECT _id ,type, title, notes, rating FROM old_books where rating > 0;");
db.execSQL("DROP TABLE IF EXISTS old_books;");
}
}
有没有更好的方法来使用教程中的实现来更新数据库而不丢失数据?我需要做的就是从“书籍”表中复制收藏夹,并在用户更新应用时将它们加载到“收藏夹”表中。
【问题讨论】:
-
copyDataBase()调用应该做什么? -
@CL。 copyDatabase() 将数据库从 APK 复制到设备。费用如下。
private void copyDataBase() throws IOException { InputStream myInput = myContext.getAssets().open(DB_NAME); String outFileName = DB_PATH + DB_NAME; OutputStream myOutput = new FileOutputStream(outFileName); byte[] buffer = new byte[1024]; int length; while ((length = myInput.read(buffer)) > 0) { myOutput.write(buffer, 0, length); } myOutput.flush(); myOutput.close(); myInput.close(); } -
你为什么要在
onUpgrade中间这样做? -
诚然,我在许多教程中都看到了这种方法。有没有更好的办法?
标签: android database sqlite sql-update