java - 一个参数具有多个参数 - Selection 和 SelectionArgs

标签 java sqlite cursor

我遇到过这个问题:

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/

相关文章:

java - 如何将 List<Object[]> 转换为 Stream<Object>

python - Sqlite3,操作错误 : unable to open database file

ruby-on-rails - 如何在设置 Ruby on Rails 时安装 SQLite3?

android - 光标错误

java - 无法返回 Cursor 对象 - close() 从未明确称为错误

node.js - MongoDB-错误: getMore command failed: Cursor not found

java - 即使命令失败,Jenkins如何将命令输出打印到文件?

java - 更改字符串日期格式

java - 列表选择监听器 valuechanged 触发超过 2 次

sqlite - 使用 SQLite 递归连接和 group_concat