【发布时间】:2018-09-10 03:28:48
【问题描述】:
我使用下面的代码来测试列是否存在:
public static boolean isColumnExists(String tableName, String columnName) {
Cursor cursor = null;
try {
SQLiteDatabase db = getDatabase();
cursor = db.rawQuery("SELECT * FROM " + tableName + " LIMIT 0", null);
String[] cloNames = cursor.getColumnNames();
if (cloNames != null) {
for (String temp : cloNames) {
if (columnName.equalsIgnoreCase(temp)) {
return true;
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != cursor && !cursor.isClosed()) {
cursor.close();
}
}
return false;
}
hello2列初始状态不存在,将列添加到数据库后,下面的测试仍然告诉该列不存在,第二次尝试会导致重复列的错误,不是正确。
if (!isColumnExists("PositionCache", "hello2")) {
// First try will insert column to database
getDatabase().execSQL("alter table PositionCache add hello2 Integer default 0");
}
if (!isColumnExists("PositionCache", "hello2")) {
// Second try will give and error about duplicate column of hello2
getDatabase().execSQL("alter table PositionCache add hello2 Integer default 0");
}
我需要知道这种异常现象的原因。
如果我在方法isColumnExists 中将SELECT * FROM 更改为select * from,那么一切都会变得正常。
【问题讨论】: