简体   繁体   English

在升级应用程序时删除SQLite数据库

[英]Dropping SQLite database on upgrading application

I implemented an Android application which use Sqlite database. 我实现了一个使用Sqlite数据库的Android应用程序。

When I release a new version of my application (not in playStore), I upload it on my server, so, if the old application is running, calling web service, can understand that new version is available. 当发布新版本的应用程序时(不在playStore中),我将其上传到服务器上,因此,如果旧的应用程序正在运行,则调用Web服务可以理解新版本可用。 So, new version is downloaded and installed. 因此,将下载并安装新版本。

When the application is overinstalled, the database is not dropped, so if I need to do any changes of my database I need to use the method: 当应用程序被过度安装时,数据库不会被删除,因此,如果我需要对数据库进行任何更改,则需要使用以下方法:

public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion)

This is fine, unless I need to do many changes in my database. 很好,除非我需要在数据库中进行很多更改。 In this case, the code becomes unreadable. 在这种情况下,代码变得不可读。 So I would to delete the database and create a new one. 因此,我将删除数据库并创建一个新数据库。

How can I perform this task? 如何执行此任务?

EDIT : What about using context.deleteDatabase(DATABASE_NAME); 编辑 :怎么样使用context.deleteDatabase(DATABASE_NAME); ?

For throw-away databases (where the data is eg a cached copy of data available in the cloud) I usually make onUpgrade() just call onCreate() and make onCreate() execute DROP TABLE IF EXISTS <tablename> before creating the tables. 对于一次性数据库(数据是例如云中可用数据的缓存副本),我通常在创建表之前先使onUpgrade()只需调用onCreate()并让onCreate()执行DROP TABLE IF EXISTS <tablename>

For example: 例如:

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  onCreate(db);
}

@Override
public void onCreate(SQLiteDatabase db) {
  db.execSQL("DROP TABLE IF EXISTS foo");
  db.execSQL("CREATE TABLE foo(bar INTEGER, baz TEXT");
}

you can think about this one 你可以考虑一下

keep a trace of your upgrade using a flag in shared preference. 使用共享首选项中的标记跟踪升级。 when you are downloading new version then set the flag to true. 当您下载新版本时,请将标志设置为true。 on every launch check the flag. 每次启动时检查标志。 if the flag is true then recreate the database and set the flag false. 如果该标志为true,则重新创建数据库并将标志设置为false。

I havn't tried similar things but I think it should work in your case. 我没有尝试过类似的方法,但我认为这应该适合您的情况。

and to delete database context.deleteDatabase(DATABASE_NAME); 并删除数据库context.deleteDatabase(DATABASE_NAME);

如果您只想重新创建整个数据库,只需将每个表都放在旧表中即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM