调用构造器DBHelper中super里面的方法,增大newVersion的值,就会自动执行onUpgrade();增加数据库字段的sql语句: String upgradeGoods = “alter table Person add column " + addColGoods + " text”;db.execSQL(upgradeGoods);
private static int newVersion = 1;
public DBHelper(DBConfig dbConfig) {
super(mContext, dbConfig.getDbName(), null, newVersion);
mDBConfig = dbConfig;
Log.e("wy", "数据库版本号: " + dbConfig.getDbVersion() + "数据库名称:" + dbConfig.getDbName());
}
全代码
package com.wintec.huashang.dbUtil;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
/**
* Created by Administrator on 2016/5/27.
*/
public class DBHelper extends SQLiteOpenHelper {
private static Context mContext;
private DBConfig mDBConfig;
// 数据库版本号,初始版本号为1
private static int newVersion = 1;
public static void init(Context context) {
mContext = context;
}
public DBHelper(DBConfig dbConfig) {
super(mContext, dbConfig.getDbName(), null, newVersion);
mDBConfig = dbConfig;
Log.e("wy", "数据库版本号: " + dbConfig.getDbVersion() + "数据库名称:" + dbConfig.getDbName());
}
@Override
public void onCreate(SQLiteDatabase db) {
Log.e("wy", "run: " + "创建表了");
db.execSQL("create table Person(_id integer primary key autoincrement,idc integer,itemCode text,name text,price real,unitId integer,classifyId integer,classifyName text,previewImage text,searchKey text,parentClassifyId integer,parentClassifyName text,unitPrint text)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.e("wy", "run: " + "执行数据库更新方法");
if (mDBConfig.getOnUpgradeListener() != null) {
mDBConfig.getOnUpgradeListener().onUpgrade();
}
//升级数据库,不改变表结构 注意空格
//添加列 addcol_goods2 , text 为字符串数据类型 ,person为表名
//alter table person add column addcol_goods2 text
//添加的列名
String addColGoods = "addcol_goods";
//添加列的sql语句
String upgradeGoods = "alter table Person add column " + addColGoods + " text";
//执行sql语句 一次只能添加一个字段
db.execSQL(upgradeGoods);
// if(oldVersion != newVersion)
// {
// switch (newVersion)
// {
第二个版本
// case 2:
//
// //升级数据库,不改变表结构 注意空格
// //添加列 addcol_goods2 , text 为字符串数据类型 ,person为表名
// //alter table person add column addcol_goods2 text
// //添加的列名
// String addColGoods = "addcol_goods";
// //添加列的sql语句
// String upgradeGoods = "alter table Person add column "+ addColGoods+" text";
// //执行sql语句 一次只能添加一个字段
// db.execSQL(upgradeGoods);
//
// break;
//
//
// }
// }
}
}
https://www.cnblogs.com/CharlesGrant/p/9144253.html
https://blog.csdn.net/xiaol206/article/details/80161363