原始完成于:2015-04-27 19:28:22
提供一种思路,优雅的处理Android数据库升级的问题,直接上代码:
1 package com.example.databaseissuetest;
2
3 import android.content.Context;
4 import android.database.sqlite.SQLiteDatabase;
5 import android.database.sqlite.SQLiteOpenHelper;
6 import android.text.TextUtils;
7 import android.util.Log;
8
9 public class DatabaseHelper extends SQLiteOpenHelper {
10 public static final String DB_NAME = "test_db";
11
12 private static final String[] COL_SQLS = {
13 "create table test_tb (id integer primary key autoincrement, name text, age int)",
14 "alter table test_tb add class text",
15 "alter table test_tb add friends integer default 3",
16 };
17
18 public DatabaseHelper(Context context) {
19 super(context, DB_NAME, null, COL_SQLS.length);
20 Log.e("David", "DatabaseHelper");
21 }
22
23 @Override
24 public void onCreate(SQLiteDatabase db) {
25 Log.e("David", "onCreate");
26 onUpgrade(db, 0, COL_SQLS.length);
27 }
28
29 @Override
30 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
31 Log.e("David", "onUpgrade oldVersion = " + oldVersion);
32 Log.e("David", "onUpgrade newVersion = " + newVersion);
33 for (int i = oldVersion; i < COL_SQLS.length; i++) {
34 String sql = COL_SQLS[i];
35 if (!TextUtils.isEmpty(sql)) {
36 db.execSQL(sql);
37 }
38 }
39 }
40 }