如:数据库为mysql,字段id类型为int。
select id,name from table where id in (?)
该如何传递参数? PreparStatement.setString("1,2,3")只能查询id=1的情况,从第一个逗号后被截取了?
处女贴,谢谢!
不考虑java,那就改一下sql
[code="sql"]select * from table
where instr(concat(',','1,2,3',','),concat(',',id,',')) > 0[/code]
String sql = "select id,name from table where id in (:ids)";
SQLQueryqueryObject=getSession().createSQLQuery(sql);
queryObject.setParameterList("ids",ids.split(","));
queryObject.list();
得这样写哦
select id,name from table where id in (?,?,?)
PreparStatement.setString("1")
PreparStatement.setString("2")
PreparStatement.setString("3")
"1,2,3",你知道这个字符串吧
String str = "1,2,3";
String[] array = str.split(",");
根据数组的长度加问号
可以不使用问号 直接拼装sql语句
遍历参数列表
String sql = "select id,name from table where id in ( "
for(i=0;i<arr.length;i++){
if(i!=arr.length-1){
sql += arr[i]+',';
}else{
sql += arr[i]+")"
}
}
然后直接执行sql语句
不能拼sql,遍历sql?列表设置参数就行了
sql =select id,name from table where id in (。。。)
split(",")
for(..){
ps.set。。。
}
一个问号解决不了,一个问号是代表一个占位符。
写多个问号也不麻烦
[quote]如果一定只能使用一个?将参数传递进去,有没有可能实现?[/quote]
不行,所以一般不建议直接在代码里用in,通常in都是配合子查询使用。
不能用占位符,直接用+号连接生成sql语句:
[code="java"]
String ids = "1,2,3";
String sql = "select id,name from table where id in (" + ids + ")";
[/code]
上面的你可以用一个?传递看看