项目上线之后,后续的迭代更新原先数据库中定义的字段可能不在满足我们项目的需求,这就牵涉到数据库的版本升级,话不多说以下为大家主要讲解在数据库版本升级中使用的主要方法:
/** * 数据库操作类 */
public class MySqlitehelper extends SQLiteOpenHelper { private static final String DATABASENAME = "news.db"; private static int version = 1;//数据库初始版本 private static int newversion = 2;//第一次升级数据库增加字段 data_id private static int newSqlVersion = 3;//第二次升级数据库再次增加字段 isRead //首页缓存 private String NewsShow_Table = "NewsShow"; private String createNewsShowTable = "create table " + NewsShow_Table + "(_id integer primary key autoincrement,ctype varchar,title varchar," + "source varchar,source_type varchar,type varchar," + "detail_a varchar,url varchar,data_id varchar,isRead varchar)"; public MySqlitehelper(Context context) { super(context, DATABASENAME, null, newSqlVersion);//version数据库创建版本号 升级时需改变 } private static MySqlitehelper instance = null; public static MySqlitehelper getInstance(Context context) { if (instance == null) { instance = new MySqlitehelper(context); } return instance; } @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { int version = sqLiteDatabase.getVersion(); if (0 == version) { sqLiteDatabase.execSQL(createNewsShowTable); //首页缓存 LogUtils.e("----onCreate", "sqlite create sqlVersion:" + version); } } /** * 数据库升级主要使用该方法 * * @param db * @param oldVersion 先前数据库版本号 * @param newVersion 升级后版本号 */ @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { LogUtils.e("----sqlite update", " ---> oldVersion:" + oldVersion + " newVersion:" + newVersion); if (newVersion > oldVersion) { if (1 == oldVersion) { db.execSQL("alter TABLE NewsShow add column data_id varchar"); db.execSQL("alter TABLE NewsShow add column isRead varchar"); LogUtils.e("----upGrade ", "oldVersion:" + oldVersion + " sqlite add column......"); } if (2 == oldVersion) { db.execSQL("alter TABLE NewsShow add column isRead varchar"); LogUtils.e("----upGrade ", "oldVersion:" + oldVersion + " sqlite add column......"); } } } }