将字符串数组传递给预准备语句数组 (JDBC + SQLServer)



>我正在尝试将字符串数组传递给预准备语句,但它返回以下异常:

java.sql.SQLFeatureNotSupportedException: This operation is not supported.
at com.microsoft.sqlserver.jdbc.SQLServerConnection.createArrayOf(SQLServerConnection.java:2763)
at entity.dao.getRecords(Dao.java:168)
at entity.dao.main(Dao.java:227)

我的代码是:

public List<Record> getRecords() throws SQLException {
String sql = "select * from table where clause in (?)";
PreparedStatement ps = this.connection.prepareStatement(sql);
List<String> strings = new ArrayList<>();
strings.add("string1");
strings.add("string2");
strings.add("string3");
Array array = this.connection.createArrayOf("VARCHAR", strings.toArray());
ps.setArray(1, array);
ResultSet executeQuery = ps.executeQuery();
List<Record> records = new ArrayList<Record>();
Record record;
while (executeQuery.next()) {
// ...
}
return records;
}

异常的行是Array array = this.connection.createArrayOf("VARCHAR", strings.toArray());

这是我尝试创建数组的时候。

我已经搜索了如何传递数组,每个人都告诉这样做,但似乎不适用于 SQLServer。

您可以使用,或者,createQuery statemen(实体管理器(

String sql= "select * from Table table where table.clause IN :clauses"; 
Query query = em.createQuery(sql, Record.class);
List<String> strings = new ArrayList<>();
strings.add("string1");
strings.add("string2");
strings.add("string3");
query.setParameter("clauses", strings );
List<Record> result= query .getResultList();

最新更新