Android Sqlite資料庫更新,在Android APP開發之中,非常常見:
在确定原來的資料庫版本号之後,在原來資料庫版本号+1,就會執行onUpgrade方法,進行資料庫更新操作:

在onUpgrade方法中,執行alter table student_table add age integer null 語句:
package com.liudeli.day2.sqlite.db;
import android.content.Context;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class MySQLiteOpenHelper extends SQLiteOpenHelper {
/**
* 資料庫的名稱
*/
private static final String DATABASE_NAME = "PersonDB.db";
/**
* 資料庫的版本号,以後要更新資料庫,修改版本号為 +1 即可
*/
private static final int DATABASE_VERSION = ;
private static MySQLiteOpenHelper instance;
/**
* 單例模式
* @param context 傳入上下文
* @return 傳回MySQLiteOpenHelper對象
*/
public static MySQLiteOpenHelper getInstance(Context context) {
if (null == instance) {
synchronized (MySQLiteOpenHelper.class) {
if (null == instance) {
instance = new MySQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
}
}
}
return instance;
}
// 構造方法不對外暴露
private MySQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
// 構造方法不對外暴露
private MySQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version, DatabaseErrorHandler errorHandler) {
super(context, name, factory, version, errorHandler);
}
// 初始化操作,會執行onCreate
@Override
public void onCreate(SQLiteDatabase db) {
// 建立一個 student_table表
db.execSQL("create table student_table(_id integer primary key autoincrement, name text);");
}
// 用于更新資料庫,當Version 變動了,就會調用onUpgrade方法
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("alter table student_table add age integer null");
}
}
----------
生成完成:
執行更新前的結果:
執行更新後的結果,多了一個age列:
謝謝大家的觀看,更多精彩技術部落格,會不斷的更新,請大家通路,
劉德利CSDN部落格, http://blog.csdn.net/u011967006