简体   繁体   English

SQLite检查列是否存在

[英]SQLite Check if column exist or not

I want to check columns (not value) at agregasi table, if columns exist do something, but if columns does not exist show/print message 'Column does not exist' . 我想检查agregasi表上的列(不是值),如果存在列则执行某些操作,但是如果列不存在,则显示/打印消息“列不存在” I could run code below while columns exist: 当列存在时,我可以在下面运行代码:

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)
}

But i have problem when columns name i change on purpose (to check). 但是,当我故意更改列名(以进行检查)时,我遇到了问题。 What should i do to print error message (in android/java way)? 我应该如何打印错误消息(以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

You're looking for getColumnIndex(String columnName) . 您正在寻找getColumnIndex(String columnName)

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

Here's a general method you can use to check whether a particular column exists in a particular table: 这是可用于检查特定表中是否存在特定列的常规方法:

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();
        }
    }
}

Try this it works fine :) 试试这个,它很好:)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM