SQLite 中使用 PRAGMA 判断指定表中的 字段/列 是否存在

 SQL语句执行效果

SQLite 中使用 PRAGMA 判断指定表中的 字段/列 是否存在_第1张图片 语句执行效果图

 执行代码

/**
 * 检查列存在
 * @param db 数据库
 * @param tableName 表名
 * @param columnName 列名
 * @return 如果存在返回:true,否则:false
 */
private boolean columnExists(SQLiteDatabase db, String tableName, String columnName) {
    boolean returnBool = false;
    tableName = tableName.toLowerCase();
    columnName = columnName.toLowerCase();
    String sql = String.format("PRAGMA table_info('%s')", tableName);
    Cursor cursor = null;
    try {
        // 结果列: cid[INTEGER], name,type [STRING], notnull[INTEGER], dflt_value[],pk[INTEGER]
        cursor = db.rawQuery(sql, null);
        // 检查表架构中是否存在列
        while (cursor.moveToNext()) {
            if (columnName.equals(cursor.getColumnName(cursor.getColumnIndex("name")))) {
                returnBool = true;
                break;
            }
        }
    } catch (Exception exception) {
        exception.printStackTrace();
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    return returnBool;
}

转载请注明出处!

你可能感兴趣的:(Java,Android)