我遇到过这个问题:
Caused by: java.lang.IllegalArgumentException: Cannot bind argument at index 3 because the index is out of range. The statement has 1 parameters.
结果是:
String where = "id_1 = 50 AND id_2 = ?";
//The String[] is ideally of dynamic length and not necessarily 3 in size.
String[] whereArgs = {"60", "61", "62"};
cursor.setSelection(where);
cursor.setSelectionArgs(whereArgs);
我只是以错误的方式使用它。我已经意识到了这一点。但我认为这清楚地表明了我想要实现的目标。
我的问题: 有没有办法将不同长度和参数的数组插入到单个参数中?我错过的任何最佳实践。我是否只是让自己陷入了糟糕的境地?
我可能正在寻找的 SQL 语句:
WHERE id_1 = 50 AND ((id_2 = 60) OR (id_2 = 61) OR (id_2 = 62))
我能想到的解决问题的唯一方法是创建一个字符串,并在循环中以 String[] 的长度为基础,在每次迭代中添加 OR (id_2 = xx) 。对我来说,这听起来并不是一个很好的解决方案。
感谢您的宝贵时间!
最佳答案
一般来说,动态构造 WHERE 子句是正确的解决方案。使用 StringBuilder.append()
而不是 +
来节省一些字符串构造开销。
在某些情况下,您可能还只想发出多个语句。所以而不是
select from table where id_1 = 50 AND (id_2 = ? OR id_2 = ? OR id_2 = ?);
你可以做 Batch的
select from table where id_1 = 50 AND (id_2 = ?);
select from table where id_1 = 50 AND (id_2 = ?);
select from table where id_1 = 50 AND (id_2 = ?);
关于java - 一个参数具有多个参数 - Selection 和 SelectionArgs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30636278/