in子句和占位符我试图在Android中执行以下SQL查询: String names = "'name1', 'name2"; // in the code this is dynamically generated
String query = "SELECT * FROM table WHERE name IN (?)";
Cursor cursor = mDb.rawQuery(query, new String[]{names});然而,Android并没有用正确的值代替问号。但是,我可以这样做,但这并不能防止SQL注入: String query = "SELECT * FROM table WHERE name IN (" + names + ")";
Cursor cursor = mDb.rawQuery(query, null);我如何才能绕过这个问题,并能够使用IN子句?
3 回答
慕的地6264312
TA贡献1817条经验 获得超6个赞
String[] names = { "name1", "name2" }; // do whatever is needed first
String query = "SELECT * FROM table"
+ " WHERE name IN (" + TextUtils.join(",", Collections.nCopies(names.length, "?")) + ")";Cursor cursor = mDb.rawQuery(query, names);
哈士奇WWW
TA贡献1799条经验 获得超6个赞
"?, ?, ..., ?"
String makePlaceholders(int len)len
String[] names = { "name1", "name2" }; // do whatever is needed firstString query = "SELECT * FROM table"
+ " WHERE name IN (" + makePlaceholders(names.length) + ")";Cursor cursor = mDb.rawQuery(query, names);String makePlaceholders(int len) {
if (len < 1) {
// It will lead to an invalid query anyway ..
throw new RuntimeException("No placeholders");
} else {
StringBuilder sb = new StringBuilder(len * 2 - 1);
sb.append("?");
for (int i = 1; i < len; i++) {
sb.append(",?");
}
return sb.toString();
}}- 3 回答
- 0 关注
- 954 浏览
添加回答
举报
0/150
提交
取消
