前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Android开发(23)数据库升级

Android开发(23)数据库升级

作者头像
张云飞Vir
发布2020-03-16 15:14:49
6750
发布2020-03-16 15:14:49
举报
文章被收录于专栏:写代码和思考写代码和思考

概述

我这里说的数据库版本指的是: 我们的应用的程序的数据库的用户版本(user_version).比如说下面的情形:

2013年4月,我们第一次 发布了 我们的应用,数据库版本是1。 2013年5月,我们第二次 发布了 我们的应用,数据库版本是2。由于业务需要,我们更改了数据库里的某个表的表结构。

这时候就有这样的难题出现:

有些用户已经下载了4月份的版本1,并且已经使用了,很多数据存储在数据库了,这个时候,他想安装新的版本2,怎么办? 怎么才能让数据不丢失?

有的用户直接装了5月份的版本,那这些用户就直接使用了新的表结构格式。

可能以后还有版本3,4,N,怎么保证“数据不丢失的情况下“让用户手机里的数据库跟着升级?

实现

SQLiteOpenHelper 中的 onUpgrade方法可以帮我们实现它,那么它是如何工作呢? 我们该如何使用他?下面先说说使用它的方式。

刚开始

我们在4月份数据库建立时,使用下面的方式

代码语言:javascript
复制
public class MyDbHelper1 extends SQLiteOpenHelper{
    public final static int DB_VERSION = 1;
    public final static String DB_NAME = "mydb.db";
    public final String TABLE_NAME = "tbl_data";
    public final String COL_UID = "uid";
    public final String COL_ITSVALUE = "itsvalue";
    public final String COL_CREATEDDATE = "createddate";
    
    public MyDbHelper1(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String sql = "create table ["+TABLE_NAME+"] ( [uid] int identity primary key,[itsvalue] nvarchar(200),createddate TIMESTAMP default (datetime('now', 'localtime')) )";
        db.execSQL(sql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        
    }
}

我们看到,在这里,我们的onCreate方法里,写个建表的语句,这个表有3个字段。

我们注意看下数据库的版本,是1

升级

[时间飞逝]..............................

于是到了五月份,由于业务需要,我们想添加新的字段到这个表里。我们这样写代码:

代码语言:javascript
复制
public class MyDbHelper2 extends SQLiteOpenHelper{
    public final static int DB_VERSION = 2;
    public final static String DB_NAME = "mydb.db";
    public final String TABLE_NAME = "tbl_data";
    public final String COL_UID = "uid";
    public final String COL_ITSVALUE = "itsvalue";
    public final String COL_CREATEDDATE = "createddate";
    public final String COL_DESC = "desc";
    
    
    public MyDbHelper2(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }
    
    @Override
    public void onCreate(SQLiteDatabase db) {
        //创建新的数据库时。已经 有新列desc了。
        String sql = "create table ["+TABLE_NAME+"] ( [uid] int identity primary key,[itsvalue] nvarchar(200),createddate TIMESTAMP default (datetime('now', 'localtime')),[desc] nvarchar(300) )";
        db.execSQL(sql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        if(oldVersion == 1 && newVersion == 2){
            //从版本1到版本2时,增加了一个字段 desc
            String sql = "alter table ["+TABLE_NAME+"] add [desc] nvarchar(300)";
            db.execSQL(sql);
        }
        
    }

这个时候,onCreate方法里,是新的建立表的方式。 而不同的是 onUpgrade方法里我们检测了这样的变化, 如果 是从版本1到版本2,我们执行了一段”添加列的sql语句“。 也就是说,当检测到数据库需要升级时,执行这些 用于升级数据库的sql。

通过上面的方式,我们就完成了一次的数据库升级的操作。 android会判断 数据库的版本号,并自动的调用onUpgrade方法。

扩展内容:如何数据库文件的版本

我们通过 SQLite Expert 软件(运行在windows下)。可以看到的这个数据库文件有个属性 user_version。 它是sqlite数据库的 "PRAGMA " 参数。执行 PRAGMA + sql有可以获得一些数据库文件的元数据信息。

比如:

代码语言:javascript
复制
    PRAGMA schema_version; 
    PRAGMA schema_version = integer ; 
    PRAGMA user_version; 
    PRAGMA user_version = integer ;
    The pragmas schema_version and user_version are used to set or get the value of the schema-version and user-version, respectively. The schema-version and the user-version are big-endian 32-bit signed integers stored in the database header at offsets 40 and 60, respectively.
    The schema-version is usually only manipulated internally by SQLite. It is incremented by SQLite whenever the database schema is modified (by creating or dropping a table or index). The schema version is used by SQLite each time a query is executed to ensure that the internal cache of the schema used when compiling the SQL query matches the schema of the database against which the compiled query is actually executed. Subverting this mechanism by using "PRAGMA schema_version" to modify the schema-version is potentially dangerous and may lead to program crashes or database corruption. Use with caution!
    The user-version is not used internally by SQLite. It may be used by applications for any purpose.

在数据库中,我们可以执行 sql语句来查询它:

代码语言:javascript
复制
PRAGMA main.user_version 

或者来设置它的值,执行下面的语句

代码语言:javascript
复制
PRAGMA main.user_version = 1

更多内容参考sqlite的官方描述。

参考

http://www.sqlite.org/pragma.html

http://dev.10086.cn/cmdn/bbs/thread-25063-1-1.html

http://blog.sina.com.cn/s/blog_6ffbcfdb0100vjhs.html

http://stackoverflow.com/questions/12778551/how-to-check-sqlite-database-file-and-get-my-defined-database-user-version

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 概述
  • 实现
    • 刚开始
    • 升级
    • 扩展内容:如何数据库文件的版本
    • 参考
    相关产品与服务
    数据库
    云数据库为企业提供了完善的关系型数据库、非关系型数据库、分析型数据库和数据库生态工具。您可以通过产品选择和组合搭建,轻松实现高可靠、高可用性、高性能等数据库需求。云数据库服务也可大幅减少您的运维工作量,更专注于业务发展,让企业一站式享受数据上云及分布式架构的技术红利!
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档