如何使用PreparedStatement传递Integer值列表

时间:2014-09-04 20:13:13

标签: java mysql list prepared-statement

我尝试编写一个代码,用于在MySql DB上创建一个SELECT

SELECT MESE,IMPORTO,ANNO FROM VISTASTATISTICHEMENSILI WHERE ANNO in(?)

所以,我想传递一个Integer值列表,如下所示:

PreparedStatement stmt = db.prepareStatement(queryDettaglio);
Integer[] myArr = new Integer[2];
myArr[0] = 1;
myArr[1] = 2;
stmt.setArray(1, db.createArrayOf("INTEGER", myArr));  
ResultSet rs = stmt.executeQuery();

因此,当我尝试运行此代码时出现此错误:

DEBUG [AWT-EventQueue-0] (MyLog4J.java:45) - java.sql.SQLFeatureNotSupportedException
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    at java.lang.Class.newInstance0(Class.java:357)
    at java.lang.Class.newInstance(Class.java:310)
    at com.mysql.jdbc.SQLError.notImplemented(SQLError.java:1332)
    at com.mysql.jdbc.JDBC4Connection.createArrayOf(JDBC4Connection.java:58)

当我解决它?

Reguards

2 个答案:

答案 0 :(得分:1)

您无法将数组传递给?在准备好的声明中。正确的方法是避免所有注射攻击的可能性如下:

StringBuilder idList = new StringBuilder()
for (int id : myArr) {
   if (idList.length() > 0) {
     idList.append(",");
   }
   idList.append("?");
}
PreparedStatement ps = con.prepareStement("SELECT MESE,IMPORTO,ANNO FROM VISTASTATISTICHEMENSILI WHERE ANNO in("+idList+");
for (int i = 0; i < myArr.length; i++) {
  ps.setInt(i+1,myArr[i]);
}

基本上你正在用正确的数字构建一个准备好的声明?标记然后设置参数。

因为myArr被声明为Integer []数组,所以你也可以这样做:

StringBuilder idList = new StringBuilder()
for (int id : myArr) {
   if (idList.length() > 0) {
     idList.append(",");
   }
   idList.append(id);
}
Statement stmt = con.createStatement();
stmt.executeQuery("SELECT MESE,IMPORTO,ANNO FROM VISTASTATISTICHEMENSILI WHERE ANNO in("+idList+");

注射没有问题,因为整数可能没有注入字符(如果它们存在,它们就不会是整数)

答案 1 :(得分:0)

尝试在for循环中手动绑定n个整数。

在此之前你应该创建?,?,...,? sql中的模式。 祝你好运。

import org.apache.commons.lang3.StringUtils;

/*
 * example: for n=4 creates pattern: ?,?,?,?
 */
public String createInListPattern(int n) {
    return StringUtils.repeat("?", ",", n);
}

public void doSelect(Integer[] myArr, Connection conn) {
    int size = myArr.length;
    String sql = "SELECT MESE,... FROM TABLE WHERE ANNO in ("
                    + createInListPattern(size) + ")";

    // be sure to properly handle sql exceptions
    PreparedStatement stmt = conn.prepareStatement(sql);

    // bind parameters
    for (int i = 0; i < size; i++) {
        stmt.setInt(i + 1, myArr[i]);
    }

    // execute query
    ResultSet rs = stmt.executeQuery();
}