Android SQLiteOpenHelper Sqlite数据库升级onUpgrade

Android Sqlite数据库升级,在Android APP开发之中,非常常见:

在确定原来的数据库版本号之后,在原来数据库版本号+1,就会执行onUpgrade方法,进行数据库升级操作:

在onUpgrade方法中,执行alter table student_table add age integer null 语句:

package com.liudeli.day2.sqlite.db;
import android.content.Context;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class MySQLiteOpenHelper extends SQLiteOpenHelper {
    /**
     * 数据库的名称
     */
    private static final String DATABASE_NAME = "PersonDB.db";
    /**
     * 数据库的版本号,以后要升级数据库,修改版本号为 +1 即可
     */
    private static final int DATABASE_VERSION = 2;
    private static MySQLiteOpenHelper instance;
    /**
     * 单例模式
     * @param context 传入上下文
     * @return 返回MySQLiteOpenHelper对象
     */
    public static MySQLiteOpenHelper getInstance(Context context) {
        if (null == instance) {
            synchronized (MySQLiteOpenHelper.class) {
                if (null == instance) {
                    instance = new MySQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
                }
            }
        }
        return instance;
    }
    // 构造方法不对外暴露
    private MySQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }
    // 构造方法不对外暴露
    private MySQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version, DatabaseErrorHandler errorHandler) {
        super(context, name, factory, version, errorHandler);
    }
    // 初始化操作,会执行onCreate
    @Override
    public void onCreate(SQLiteDatabase db) {
        // 创建一个 student_table表
        db.execSQL("create table student_table(_id integer primary key autoincrement, name text);");
    }
    // 用于升级数据库,当Version 变动了,就会调用onUpgrade方法
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("alter table student_table add age integer null");
    }
}
----------
生成完成:


执行升级前的结果:

执行升级后的结果,多了一个age列:

转载于:Android SQLiteOpenHelper Sqlite数据库升级onUpgrade_onupgrade方法_刘德利_Android的博客-CSDN博客

猜你喜欢

转载自blog.csdn.net/weixin_42602900/article/details/131170898