/** * @author liulp */ public class MysqLite extends sqliteOpenHelper { private volatile sqliteDatabase db; //建表语句 此部分只是用户第一次安装的时候会在oncreate方法中调用 //请注意CREATE部分不要做任何修改 所有的数据库修改都应该在 update_sql中进行 String CREATE[] = new String[] { "create table " + TB_USER + " (tid integer primary key,name varchar(50));","Create table " + TB_USER_REPORT + "( tid integer primary key,uid integer,score integer);",}; //升级部分的 private static UpDateGrades[] updategrades = new UpDateGrades[] { new UpDateGrades() { @Override public void doupDateGrade(sqliteDatabase db) { // TODO Auto-generated method stub db.execsql("create table " + TB_USER_REPORT + " (tid integer primary key,uid interger,score interger);"); } },}; private static final String DBNAME = "popo"; // public static final String TB_USER = "user"; public static final String TB_USER_REPORT = "user_report"; String TAG = "sqlITE"; private static volatile MysqLite MysqLite = null; private MysqLite(Context context) { super(context,DBNAME,null,updategrades.length + 1); Log.v("MysqLite"," version=" + updategrades.length + 1); db = getWritableDatabase(); updategrades = null; CREATE = null; } public static MysqLite instance(Context context) { if (MysqLite == null) { synchronized (MysqLite.class) { if (MysqLite == null) MysqLite = new MysqLite(context); } } return MysqLite; } public sqliteDatabase getsqliteDatabase() { if (db == null) { synchronized (this) { if (db == null) db = getWritableDatabase(); } } else { if (db.isOpen() == false) { synchronized (this) { if (db.isOpen() == false) { db = null; db = getWritableDatabase(); } } } } return db; } /** * 执行创建 数据库语句 */ @Override public void onCreate(sqliteDatabase db) { // TODO Auto-generated method stub Log.v(TAG,"MyDBHelper onCreate"); for (String sql : CREATE) { db.execsql(sql); } } //执行升级语句 @Override public void onUpgrade(sqliteDatabase db,int oldVersion,int newVersion) { // TODO Auto-generated method stub Log.v(" Version","oldVersion=" + oldVersion + ",newVersion=" + newVersion); for (int i = oldVersion; i < newVersion; i++) { updategrades[i - 1].doupDateGrade(db); } } //升级语句接口 interface UpDateGrades { void doupDateGrade(sqliteDatabase db); }; }
主要修改时把升级操作改成了一个借口方法,这样可以实现更复杂的需求分析,并且多个修改语句可以在一个方法中执行,版本号可以和我们发布的App版本比较更贴近。
原文链接:https://www.f2er.com/sqlite/200304.html