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

10 篇文章 0 订阅

 SQL语句执行效果

语句执行效果图
语句执行效果图

 执行代码

/**
 * 检查列存在
 * @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.getString(cursor.getColumnIndex("name")))) {
                returnBool = true;
                break;
            }
        }
    } catch (Exception exception) {
        exception.printStackTrace();
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    return returnBool;
}

转载请注明出处!

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值