[英]Upgrading the SQLite Database of a Production Android App, is this Correct?
As the title says, I have a production Android app with about 1000 installs. 正如标题所说,我有一个生产Android应用程序,安装量约为1000。 I had to make a DB change in SQLite, up to this point the version of the SQLite DB has been set to version "1".
我不得不在SQLite中进行数据库更改,到目前为止,SQLite DB的版本已设置为版本“1”。
Hopefully I explain the code below sufficiently in the comments, this code resides in my SQLiteOpenHelper Class so the onUpgrade method is part of the Class: 希望我在注释中充分解释下面的代码,这段代码驻留在我的SQLiteOpenHelper类中,因此onUpgrade方法是Class的一部分:
// Provides an upgrade path for the DB when the apps version is updated.
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// First version of the DB was 1. Logic: each if statement will
// alter the DB cumulatively based on the version code. So, if the
// newVersion was version 3, there would be two if statements, one
// for oldVersion 1 and one for oldVersion 2. oldVersion 2 will
// contain the logic for upgrading from version 2 to 3, while
// oldVersion 1 will contain a combination of alter statements
// allowing the database to upgrade from version 1 directly to
// version 3.
if (oldVersion == 1) {
db.execSQL("ALTER TABLE plans ADD COLUMN " + App.CURRENCYCODE
+ " TEXT");
Locale locale = Locale.getDefault();
ContentValues content_values = new ContentValues();
content_values.put(App.CURRENCYCODE, locale.toString());
db.update(App.DBPLANS, content_values, App.ID + " > ?", new String[] {
"0"
});
}
if (oldVersion == 2) {
// Placeholder for next database upgrade instructions.
}
}
Please let me know if there are any pitfalls here. 如果这里有任何陷阱,请告诉我。 So far, it's tested fine, though I'm very concerned about messing up my first DB upgrade.
到目前为止,它测试得很好,虽然我非常担心搞乱我的第一次数据库升级。 I have a 1,000 users or so, I'd hate to lose them all.
我有1000个左右的用户,我不想失去他们。
Thanks again! 再次感谢!
When I need to update a database like this, I typically do it with a switch statement where cases fall through to one another, such as: 当我需要更新这样的数据库时,我通常使用switch语句来执行此操作,其中案例会相互渗透,例如:
switch (oldVersion) {
case 1:
// update to version 2
// do _not_ break; -- fall through!
case 2:
// update to version 3
// again, do not break;
case 3:
// you're already up to date
The benefits to this is you do not end up repeating your update statements in multiple if-statements as you continue to change the database, and adding a database update requires only adding a new case statement, not updating multiple blocks of code. 这样做的好处是,当您继续更改数据库时,最终不会在多个if语句中重复更新语句,并且添加数据库更新只需要添加新的case语句,而不是更新多个代码块。
There are sometimes exceptions to this, such as a column added in one version but then deleted in a future one, so you need to pay attention as you go. 有时会出现例外情况,例如在一个版本中添加了一列但在将来删除了一列,因此您需要注意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.