Passing an Array to a SQL query using Java's PreparedStatement

[亡魂溺海] 提交于 2019-12-18 09:38:11

问题


I've been having a little trouble passing an array into a SQL query using Java's prepared statements. I had first tried the sourceforge driver, however I would get the AbstractMethodError when I call setArray method. Not knowing the solution to that I swapped to the Microsoft sqlserver driver, but now I get a different error entirely, which is "java.sql.SQLFeatureNotSupportedException: This operation is not supported." Tried a whole bunch of things to try and resolve this but nothing appears to work.

My Java code looks similar to examples I've seen here and on the internet, and is as follows,

PreparedStatement ps = connection.prepareStatement(query);
String[] suppliers = {"21","2774","120563","3714","59"};
ps.setArray(1, connection.createArrayOf("text", suppliers));
ResultSet rs = ps.executeQuery();

Example of my SQL queries. The only line of real interest is the line before last where I have added the '?' character, which as I understand it is how I pass a parameter to a SQL Query.

productsPrices.query = select contract.supplierid as 'hotelid' \
  , round((rate.s1/money.buy)*euro.sell,0) as "single" \
  , round((rate.s2/money.buy)*euro.sell,0) as "double" \
  ,service.Name as 'roomtype' \
  ,stock.alloc - stock.taken as 'stock.available' \
  , contract.notes as 'boardType' \
  , object.name as 'occupancy' \
  ,object.cap as 'capacity' \
  ,object.mincap as 'min capacity' \
  ,stock.date as 'date' \
from stock stock \
  inner join rate rate on stock.rateid = rate.id \
  inner join contract contract on rate.contractid = contract.id \
  inner join service service on contract.serviceid = service.ID \
  inner join object object on service.objectid = object.ID \
  inner join band band on contract.termsid = band.ID \
  inner join Money money on band.moneyid = money.id \
  inner join Money euro on euro.Name  = 'Euros' \
where stock.date > getdate() \
and stock.closed = 0 \
and (stock.alloc - stock.taken) > 0 \
and stock.date > getdate() \
      and contract.supplierid in (?) \
      and contract.Finish > GETDATE()

回答1:


I solved same issue by dynamically generating string with required number of question marks. Here's a snippet:-

String param = "(";
for(int i=0;i<suppliers.length;i++){
param = param+"?,";
}
param = param.substring(0,param.length()-1);
param=param+")";

query = query + param;

PreparedStatement ps = connection.prepareStatement(query);

for(int i=0;i<suppliers.length;i++){
ps.setString(i+1,suppliers[i]);
}


来源:https://stackoverflow.com/questions/17105610/passing-an-array-to-a-sql-query-using-javas-preparedstatement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!