方法一:把数组转为字符串,然后把[ ]替换为(),在拼起来
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);
}
}