如何更新 SQLite 数据库而不丢失所有现有数据?
我正在向应用程序的 SQLite 数据库添加一个表。我所有的语法都很好,不是问题。但我在正确创建新表时遇到了一些麻烦。我添加了新表......
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
db.execSQL(CREATE_REQUESTS);
db.execSQL(CREATE_OVERRIDE);
}
我的创建方法。我有3张桌子。当我更新版本号时,出现错误“表请求(指 CREATE_REQUESTS)已被创建”。看看我的 onUpgrade 方法...
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
让我明白了 db.execSQL("DROP TABLE IF EXISTS contacts") 行,它引用 onCreate 方法中的 DATABASE_CREATE 表,用于删除旧表,然后下一行 onCreate(db);
重新创建它。我没有将请求添加到该 execSQL 行中,这就是导致错误的原因。问题是:我不想丢失已有的两个表中的数据。有没有办法像我一样添加一个表,并且不会丢失所有旧数据?谢谢。
I'm adding a table to my app's SQLite DB. All my syntax there is fine, not the issue. But I'm having some trouble getting the new table to be created properly. I added the new table....
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
db.execSQL(CREATE_REQUESTS);
db.execSQL(CREATE_OVERRIDE);
}
My on create method. I have 3 tables. When I updated the version number, I got an error saying "table requests (referring to CREATE_REQUESTS) has already been created." A look at my onUpgrade method...
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
Led me to understand that the line db.execSQL("DROP TABLE IF EXISTS contacts")
, which refers to my DATABASE_CREATE table in the onCreate method, is used to drop the old table, then the next line, onCreate(db);
recreates it. I did not add requests into that execSQL line, which is what caused the error. Here is the issue: I would rather not lose the data in the two tables I already have. Is there a way to add a table like I am trying to do, and not lose all the old data? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以在
onUpgrade
中执行任何操作。您可以使用ALTER
向表中添加新列。最坏的情况是,如果您的架构完全不同,您将必须创建新表,使用旧表中的数据填充它,然后删除旧表。
无论如何,
onUpgrade
的设计目的是为了实现平滑升级而不会丢失任何数据。这取决于您是否正确实施它。You can do anything you want in
onUpgrade
. You can useALTER
to add new columns to your table.Worst case, if your schema is completely and entirely different, you'll have to create the new table, populate it using data from the old table, and then delete the old table.
In any case,
onUpgrade
was designed to allow for a smooth upgrade without any loss of data. It's just up to you to implement it properly.如果数据库版本:6
当您升级到:7(我在 3 个表中添加 1 个新列)
其中:“DATABASE_ALTER_ADD_PAPER_PAID”是查询。
经过以上两个操作后,对于全新安装用户和应用程序升级用户来说就可以正常工作了
if DB version : 6
When you upgrade to : 7 ( I am adding 1 new column in the 3 tables)
Where : "DATABASE_ALTER_ADD_PAPER_PAID" is query.
After above two operation it will works fine for the fresh install user and app upgrade user