【问题标题】:SQLite query with selection arguments [duplicate]带有选择参数的 SQLite 查询 [重复]
【发布时间】:2016-10-05 09:37:25
【问题描述】:

我有以下 SQLite 查询:

ArrayList<Long> idList = new ArrayList<>();

// adding Long values to idList

SQLiteDatabase db = getReadableDatabase();

final String whereClause = COLUMN_DEVICE_ID + " IN (?)";
final String[] whereArgs = new String[]{TextUtils.join(", ", idList)};

Cursor cursor = db.query(TABLE_DEVICES, null, whereClause, whereArgs,
    null, null, null);

执行此查询会产生一个空的Cursor

问题的原因似乎是whereArgs String 没有插入whereClause

我调试了代码,发现CursormQuery字段被初始化为如下:

SELECT * FROM table_devices WHERE device_id IN (?)

为什么? 没有被whereArgs 取代?

提前致谢。

【问题讨论】:

标签: android sqlite android-sqlite


【解决方案1】:

解决了以下问题:

final String args = TextUtils.join(", ", ids);
final String whereClause = String.format(COLUMN_DEVICE_ID + " IN (%s)", args);

Cursor cursor = db.query(TABLE_DEVICES, null, whereClause,
    null, null, null, null);

虽然我不确定这与? + whereArgs 方法相比有多安全(关于 SQL 注入)。

【讨论】:

    猜你喜欢
    • 2011-08-14
    • 2017-08-14
    • 1970-01-01
    • 1970-01-01
    • 2015-12-09
    • 2012-03-26
    • 2021-04-02
    • 1970-01-01
    • 2021-05-02
    相关资源
    最近更新 更多