在应用开发时,可能随着需求或者其他因素,原设计的数据字段不够了需要重新新增或者删除字段,又或者创建新的表,这时我们该怎么做呢?
下面来看一个例子, 这是我们第一版开发的数据库,
package com.laomou.demo;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class SQLTest extends SQLiteOpenHelper {
private static String DB_NAME = "people";
private static int VERSION = 1;
public SQLH(Context context) {
super(context, DB_NAME, null, VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
StringBuilder sql = new StringBuilder();
sql.append("CREATE TABLE people");
sql.append("(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age TEXT);");
db.execSQL(sql.toString());
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
表结构如下
随着需求或者其他因素,可能需要添加新字段,这是我们第二版开发的数据库,
package com.laomou.demo;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class SQLH extends SQLiteOpenHelper {
private static String DB_NAME = "people";
private static int VERSION = 2;
public SQLH(Context context) {
super(context, DB_NAME, null, VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
StringBuilder sql = new StringBuilder();
sql.append("CREATE TABLE people");
sql.append("(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age TEXT);");
db.execSQL(sql.toString());
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
int upgradeVersion = oldVersion;
if (1 == upgradeVersion) {
StringBuilder sql = new StringBuilder();
sql.append("ALTER TABLE people ");
sql.append("add class TEXT");
db.execSQL(sql.toString());
upgradeVersion = 2;
}
if (upgradeVersion != newVersion) {
// Drop tables
db.execSQL("DROP TABLE IF EXISTS people");
// Create tables
onCreate(db);
}
}
}
表结构如下
再来看是如何做到升级数据库,添加字段的
更改数据库的版本
private static int VERSION = 2;
实现了onUpgrade方法
int upgradeVersion = oldVersion;
if (1 == upgradeVersion) {
StringBuilder sql = new StringBuilder();
sql.append("ALTER TABLE people ");
sql.append("add class TEXT");
db.execSQL(sql.toString());
upgradeVersion = 2;
}
if (upgradeVersion != newVersion) {
// Drop tables
db.execSQL("DROP TABLE IF EXISTS people");
// Create tables
onCreate(db);
}