Android SQLiteOpenHelper Sqlite数据库升级onUpgrade

时间:2023-03-08 19:20:23
Android SQLiteOpenHelper Sqlite数据库升级onUpgrade

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

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

Android SQLiteOpenHelper Sqlite数据库升级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");
}
} ----------
生成完成:

Android SQLiteOpenHelper Sqlite数据库升级onUpgrade


执行升级前的结果:

Android SQLiteOpenHelper Sqlite数据库升级onUpgrade

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

Android SQLiteOpenHelper Sqlite数据库升级onUpgrade


谢谢大家的观看,更多精彩技术博客,会不断的更新,请大家访问,

刘德利CSDN博客, http://blog.csdn.net/u011967006