SQL中无法使用条件 IN 进行变量绑定
以下代码可以查询到数据:
String returnStr="";
String sql="select name from table1 t where t.lot_id in ('tab1','tab2')";
System.out.println(sql);
stmt = conn.prepareStatement(sql);
rset=stmt.executeQuery();
while(rset.next())
{
returnStr= rset.getString(1);
System.out.println("returnStr:"+returnStr
}
rset.close();
st.close();
--------------------
但是为何以下代码写法却查不到数据?
String returnStr="‘";
String str=="'tab1','tab2'";
String sql="select name from table1 t where t.lot_id in (?)";
System.out.println(sql);
stmt = conn.prepareStatement(sql);
stmt.setString(1, str);
rset=stmt.executeQuery();
while(rset.next())
{
returnStr= rset.getString(1);
System.out.println("returnStr:"+returnStr
}
rset.close();
st.close();
------解决方案--------------------不好意思写错了
应该是这样
String sql = "select name from table1 t ";
if (array != null && array.length != 0) {
sql += " where t.lot_id in ("
for (int i = 0; i < array.length; i++) {
sql += + "?,"
}
sql = sql.substring(0,sql.length() - 1) + ")";
}
stmt = conn.prepareStatement(sql);
if (array != null && array.length != 0) {
for (int i = 0; i < array.length; i++) {
stmt.setString(i + 1, array[i]);
}
}