我正在尝试升级数据库。 所以下面的方法会被调用。
有5张桌子。我只想更改最后的1table。 但是在调用onupgrade时,尚未创建最后一个表,因此无法在Onupgrade方法上对其进行更改。
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int currentVersion) {
创建表后。我想检查是否不存在该列,然后再更改表。我尝试了下面的代码,但不起作用
public static void createuserTable(SQLiteDatabase db, String tableName) {
final String table = "CREATE TABLE IF NOT EXISTS "
+ tableName + " (_id INTEGER PRIMARY KEY AUTOINCREMENT, user_name TEXT, addressTEXT, phone TEXT, phone2 TEXT)";
Cursor cursor = db.rawQuery(table , null); // grab cursor for all data
int deleteStateColumnIndex = cursor.getColumnIndex("email"); // see if the column is there
if (deleteStateColumnIndex < 0) {
// missing_column not there - add it
Log.d("value dont exist","value dont exist");
}
db.execSQL(table);
}
答案 0 :(得分:1)
理论上,您应该通过遵循定义的升级机制来知道该列是否存在。
但是,如果该列易于唯一标识,则可以使用:-
public void createuserTable (SQLiteDatabase db, String tableName) {
//Force table to exist (if it doesn't then why not include the email column in the definition? (rhetorical))
final String table = "CREATE TABLE IF NOT EXISTS "
+ tableName + " (_id INTEGER PRIMARY KEY AUTOINCREMENT, user_name TEXT, addressTEXT, phone TEXT, phone2 TEXT)";
String columnName = "email"; //<<<<<<<<<< change as appropriate
String columnDefinition = " TEXT UNIQUE "; //<<<<<<<<<< change as appropriate
Cursor cursor;
if (((
cursor = db.query(
"sqlite_master",
new String[]{
"sql"
},
"sql LIKE ? AND type = 'table' AND name = ?",
new String[]{
"%" + columnName + "%",
tableName
},
null,
null,
null
)).getCount() < 0)){
db.execSQL("ALTER TABLE " + tableName +" ADD COLUMN " + columnName + columnDefinition);
}
cursor.close();
}
当然,列名不能与包含新列名的另一个列名冲突。
上面是原则代码,尚未经过测试或运行,因此可能包含一些错误。