本文参考自:这里-->https://thebhwgroup.com/blog/how-android-sqlite-onupgrade
直接上代码:
public class Sqlhelper extends SQLiteOpenHelper { public SQLiteHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } //常量值 private static final String DATABASE_NAME = "demoApp.db";//数据库名字 private static final int DATABASE_VERSION = 3;//每次App升级的时候,就要+1 public static final String COLUMN_ID = "_id"; //需要用到的表名和列名 public static final String TABLE_TEAM = "team"; public static final String COLUMN_MASCOT = "mascot"; public static final String COLUMN_CITY = "city"; public static final String COLUMN_COACH = "coach"; public static final String COLUMN_STADIUM = "stadium"; //数据库SQL语句,创建表的语句 private static final String DATABASE_CREATE_TEAM = "create table " + TABLE_TEAM + "(" + COLUMN_ID + " integer primary key autoincrement, " + COLUMN_NAME + " string, " + COLUMN_MASCOT + " string, " + COLUMN_COACH + " string, " + COLUMN_STADIUM + " string, " + COLUMN_CITY + " string);"; //数据库升级的时候,修改表的语句 private static final String DATABASE_ALTER_TEAM_1 = "ALTER TABLE " + TABLE_TEAM + " ADD COLUMN " + COLUMN_COACH + " string;"; //数据库升级的时候,修改表的语句 private static final String DATABASE_ALTER_TEAM_2 = "ALTER TABLE " + TABLE_TEAM + " ADD COLUMN " + COLUMN_STADIUM + " string;"; @Override public void onCreate(SQLiteDatabase db) { //初始化,会自动的打开或者创建数据库 db.execSQL(DATABASE_CREATE_TEAM); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { //根据版本的大小来判断是否需要执行某些语句,因为每次版本都是不一样的 //按照正常的话(也就是用户每次升级都有升),是只需要执行一次就可以,但是用户不是每一次都升级的app、 //还有就是初次安装不是从版本1开始安装app的话。你懂的 if (oldVersion < 2) { db.execSQL(DATABASE_ALTER_TEAM_1); } if (oldVersion < 3) { db.execSQL(DATABASE_ALTER_TEAM_2); } } }
代码就是上面这些,很简单,看看也就明白了。还有不明白的,就看原文吧,原文是英语,需要自己琢磨一下。
原文给出了几个错误的例子,我觉得需要学习的小伙伴还是值得去看一下原文,看过了,下次自己也就不会这样写了。