所以,我已经在Playstore上安装了我的应用.
现在,我想在我的应用程序中向数据库添加一列.为此,我必须升级数据库,这可以通过更改数据库版本来完成.
用户已经在数据库中保存了一些东西,当我上传应用程序的更新版本(数据库已更改版本)时,它将创建一个新的数据库,并且用户将丢失他/她在他/中拥有的所有东西.她的数据库.
这个问题有什么解决方案?以及如何将旧数据库的内容备份/还原到新数据库? (我知道如何通过简单地以编程方式将数据库复制粘贴到外部存储来备份数据库).
解决方法:
您可以使用onUpgrade()方法进行处理.
像这样:
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion == 1 && newVersion == 2) {
db.execSQL("create temporary table people_tmp ("
+ "id integer, name text, position text, posid integer);");
db.execSQL("insert into people_tmp select id, name, position, posid from people;");
db.execSQL("drop table people;");
db.execSQL("create table people ("
+ "id integer primary key autoincrement,"
+ "name text, posid integer);");
db.execSQL("insert into people select id, name, posid from people_tmp;");
db.execSQL("drop table people_tmp;");
}
}
所以.您正在创建临时表并将所有需要的信息保存在该表中.接下来,放下表,创建一个新表,并从临时表中插入值.您可以添加其他字段,并随时将所有所需内容放在此处.
更新:
经过一番谷歌搜索后,我发现了一个更简单的解决方案:
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// If you need to add a column
if (newVersion == 2) {
db.execSQL("ALTER TABLE foo ADD COLUMN new_column INTEGER DEFAULT 0");
}
}
更改表方法将更改数据库结构而不会丢失数据.
标签:sqlite,android
来源: https://codeday.me/bug/20191120/2047217.html