SQLite检查列是否存在

时间:2015-06-06 12:18:39

标签: java android sqlite

我想检查 agregasi 表中的列(而不是值),如果列存在则执行某些操作,但是如果列不存在则显示/打印消息'列不存在& #39; 即可。 当列存在时,我可以在下面运行代码:

String keywords1={'pesawat','terbang'}; 
String sql1 = "SELECT " + keywords + " FROM agregasi"; //columns exist at agregasi table
Cursor c1 = myDbHelper.rawQuery(sql1, null);
if (c1.moveToFirst()) {
   // i can do something (no problem)
}

但是当列名称我故意改变(检查)时,我有问题。我该怎么做才能打印错误信息(用android / java方式)?

**String keywords2={'psawat','terang'};** 
String sql2 = "SELECT " + keywords + " FROM agregasi"; //columns does not exist at table 
Cursor c2 = myDbHelper.rawQuery(sql2, null);
// what should i do get error message and show/print using toast

3 个答案:

答案 0 :(得分:6)

您正在寻找getColumnIndex(String columnName)

int index = c2.getColumnIndex("someColumnName");
if (index == -1) {
    // Column doesn't exist
} else {
    ...
}

答案 1 :(得分:0)

这是一种通用方法,可用于检查特定表中是否存在特定列:

public boolean isColumnExists(SQLiteDatabase sqliteDatabase,
                              String tableName,
                              String columnToFind) {
    Cursor cursor = null;

    try {
        cursor = sqLiteDatabase.rawQuery(
                "PRAGMA table_info(" + tableName + ")",
                null
        );

        int nameColumnIndex = cursor.getColumnIndexOrThrow("name");

        while (cursor.moveToNext()) {
            String name = cursor.getString(nameColumnIndex);

            if (name.equals(columnToFind)) {
                return true;
            }
        }

        return false;
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

答案 2 :(得分:-1)

试试这个工作正常:)

Cursor res = db.rawQuery("PRAGMA table_info("+tableName+")",null);
int value = res.getColumnIndex(fieldName);