【问题标题】:Android - sqlite in clause using values from arrayAndroid - sqlite in 子句使用数组中的值
【发布时间】:2012-02-08 23:34:55
【问题描述】:

我想执行一个 sqlite 查询:

select * from table_name where id in (23,343,33,55,43);

in 子句中的值需要取自字符串数组:

String values[] = {"23","343","33","55","43"}

我怎样才能做到这一点?

【问题讨论】:

标签: android sql sqlite


【解决方案1】:

我相信一个简单的toString() 就可以解决问题:

String values[] = {"23","343","33","55","43"};
String inClause = values.toString();

//at this point inClause will look like "[23,343,33,55,43]"
//replace the brackets with parentheses
inClause = inClause.replace("[","(");
inClause = inClause.replace("]",")");

//now inClause will look like  "(23,343,33,55,43)" so use it to construct your SELECT
String select = "select * from table_name where id in " + inClause;

【讨论】:

  • 如果您的某些值来自用户输入,您可能会受到 SQL 注入攻击或至少崩溃。在将用户输入放入 sql 语句之前,您应该查看DatabaseUtils.html#sqlEscapeString(java.lang.String) 和相关函数。
  • 在进行此替换之前,您应该确保您的任何值都不包含 [ 或 ]。更好的方法是获取第一个和最后一个字符之间的子字符串并将其包装在 ( 和 )
  • 如果必须将值用引号括起来,您有什么建议?
猜你喜欢
  • 1970-01-01
  • 2011-09-09
  • 1970-01-01
  • 2016-10-14
  • 1970-01-01
  • 2011-08-25
  • 2010-11-21
  • 2015-05-07
  • 1970-01-01
相关资源
最近更新 更多