我正在使用一个类来扩展 SQLiteOpenHelper,如下所示:
public class PocketSQLite extends SQLiteOpenHelper {
public String TableNames[];
public String FieldNames[][];
public String FieldTypes[][];
public static String NO_CREATE_TABLES = "no tables";
private String message = "";
public PocketSQLite(Context context, String name, CursorFactory factory, int version, String tableNames[], String fieldNames[][], String fieldTypes[][]) {
super(context, name, factory, version);
TableNames = tableNames;
FieldNames = fieldNames;
FieldTypes = fieldTypes;
}
@Override
public void onCreate(SQLiteDatabase db) {
if (TableNames == null) {
message = NO_CREATE_TABLES;
return;
}
for (int i = 0; i < TableNames.length; i++) {
String sql = "CREATE TABLE " + TableNames[i] + "(";
for (int j = 0; j < FieldNames[i].length; j++)
sql += FieldNames[i][j] + " " + FieldTypes[i][j] + ",";
sql = sql.substring(0, sql.length() - 1);
sql += ")";
db.execSQL(sql);
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
for (int i = 0; i < TableNames[i].length(); i++) {
String sql = "DROP TABLE IF EXISTS " + TableNames[i];
db.execSQL(sql);
}
onCreate(db);
}
}
如您所见,构造函数将输入表的字段。如何更新 onUpgrade 函数以将新字段添加到现有表?
例如:
旧表(2 个字段):“姓名”、“电话”
新表(3 个字段):“姓名”、“电话”、“电子邮件”