思维:
1.当然,它是基于SQLiteOpenHelper.onCreate(第一个呼叫建立)、onUpdate(当所谓的升级计划)
2.用"脚本"(脚本制作详细方法问度娘)做数据库升级,文件名称标识相应版本号,java中依据“上一版本号、当前版本号”选择运行的脚本。
升级时,改动DB_VERSION(当前版本号)就可以。
DBManager.java:
package com.example.test; import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream; import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper; public class DBManager extends SQLiteOpenHelper { private final static String DBNAME = "mydata.db"; private final static int DB_VERSION = 1; private static DBManager instance; public DBManager(Context context) {
// TODO Auto-generated constructor stub
super(context, DBNAME, null, DB_VERSION);
} public static DBManager getThis() {
if (instance == null)
instance = new DBManager(MainActivity.getThis()); return instance;
} @Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
initDb(db, 0, DB_VERSION);
} @Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
initDb(db, oldVersion, newVersion);
} // 初始化db,运行脚本
// 注:1>运行"(oldV,newV]"(全新安装时,oldV=0)间的脚本
// 2>缺失的脚本会直接跳过
private void initDb(SQLiteDatabase db, int oldVersion, int newVersion) {
for (int i = oldVersion + 1; i <= newVersion; i++)
execDBScript(db, "db/update" + i + ".sql");
} // 运行脚本
private void execDBScript(SQLiteDatabase db, String assetName) {
try {
InputStream is = MainActivity.getThis().getAssets().open(assetName);
String stats = read(is);
execSqls(db, stats);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
} // 批运行,用";"隔开
private void execSqls(SQLiteDatabase db, String stats) {
// onCreate/onUpdate内部已带事务,多层嵌套无影响(最外层起作用)
db.beginTransaction();
String[] sqls = stats.split(";");
for (int i = 0; i < sqls.length; i++) {
String sqlStatement = sqls[i].trim();
// TODO You may want to parse out comments here
if (sqlStatement.length() > 0) {
// 捕获错误,防止运行drop时 直接越过
try {
db.execSQL(sqlStatement + ";");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
db.setTransactionSuccessful();
db.endTransaction();
} public static String read(InputStream instream) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = instream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
String ret = new String(bos.toByteArray());
return ret;
} }
db脚本: