android - 更改表并添加列,但检查该列是否已存在于 android studio
问题描述
我正在尝试升级数据库。所以下面的方法被调用。
有5张桌子。我只想更改最后一个表。但是当 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);
}
解决方案
理论上,您应该通过遵循定义的升级机制来知道该列是否存在。
但是,如果该列很容易唯一识别,那么您可以使用:-
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();
}
当然,列名不得与包含新列名的另一个列名冲突。
- 例如,如果新的列名是 col1 并说一个列存在名称 thisiscol1,那么由于 col1 将被发现是 col1 的一部分,则不会执行 ALTER 命令。
以上是原则性代码,尚未测试或运行,因此可能包含一些错误。
推荐阅读
- java - 尝试单击包含空格的超链接
- .htaccess - 如何设置 X-Frame-Options?
- python - 尝试计算最大值时出错(只能将大小为 1 的数组转换为 Python 标量)
- c# - 使用 Asp.NET MVC 将 SQL 中的 Smalldatetime 列转换或转换为字符串
- python-3.x - 用 matplotlib 绘制一个圆锥
- java - 使用多个源参数的 Mapstruct 表达式映射
- statistics - 具有恒定基年的增长公式
- docker - 无法重新启动单个节点 etcd,其中 data_dir 映射到 kubernetes 中的持久卷
- spring - 如何将弹簧安全设置从弹簧转移到弹簧靴
- jquery-ui - jquery ui-sortable 事件,beforeStop 得到错误的 index() 值