方法一:把数组转为字符串,然后把[ ]替换为(),在拼起来
public static void query(Connection conn,String[] arr ){
PreparedStatement pst=null;
ResultSet rs=null;
StringBuilder sql=new StringBuilder("select * from test_lin where id in ");
try {
String arrStr=Arrays.toString(arr).replace("[", "(").replace("]", ")");
sql.append(arrStr);
pst=conn.prepareStatement(sql.toString());
rs=pst.executeQuery();
while(rs.next()){
System.out.println("id="+rs.getString(1)+"\tname="+rs.getString(2));
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
close(rs, pst, conn);
}
}方法二:用占位符?来拼
public static void query(Connection conn,String[] arr ){
PreparedStatement pst=null;
ResultSet rs=null;
StringBuilder sql=new StringBuilder("select * from test_lin where id in ");
try {
int len=arr.length;
sql.append("(");
for(int i=0;i<len;i++){
sql.append("?");
if(i!=len-1){
sql.append(",");
}
}
sql.append(")");
pst=conn.prepareStatement(sql.toString());
for(int j=0;j<len;j++){
pst.setObject(j+1,arr[j]);
}
rs=pst.executeQuery();
while(rs.next()){
System.out.println("id="+rs.getString(1)+"\tname="+rs.getString(2));
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
close(rs, pst, conn);
}
}

本文介绍两种在Java中使用PreparedStatement批量查询数据库的方法。一种是通过将数组转换为字符串,并修改其格式来构建SQL查询;另一种则是利用占位符进行参数化查询,增强SQL语句的安全性和灵活性。
16万+

被折叠的 条评论
为什么被折叠?



