我正在使用以下代码从db2中检索订单数据,当我只传递BranchNumber并使用getWildcards()函数时它工作正常,因为有时我传递了多个分支编号。
public List<Order> getallorders(List<Branch> BranchNumber) throws SQLException {
List<Order> orders = new ArrayList<Order>();
try {
StringBuilder sb = new StringBuilder();
sb.append("SELECT ORDER_NUMBER as ordernumber,SERVICE_TYPE as service"
+ "FROM ORDER WHERE "
+ "BRANCH IN(");
sb.append(getWildCards(BranchNumber.size())).append(")").append(" WITH UR");
String query = sb.toString();
PreparedStatement statement = connection.prepareStatement(query);
for(int i=0 ; i<BranchNumber.size() ;i++)
{
statement.setInt(i+1,BranchNumber.get(i).getBranch());
}
ResultSet resultSet = statement.executeQuery();
{
while (resultSet .next()) {
Order order1 = new Order();
order1.setOrdernumber(resultSet.getInt("ordernumber"));
orders.add(order1);
}
}
}
catch (SQLException e) {
e.printStackTrace();
}
return orders;
}
private String getWildCards(int size) {
// TODO Auto-generated method stub
StringBuilder sb = new StringBuilder();
for(int i =0 ; i<size ; i++)
{
sb = (i == 0) ? sb.append("?")
: sb.append(",").append("?");
}
return sb.toString();
}
现在我需要在函数内部传递startDate和endDate来检索数据,但是readystatement没有使用传递的值格式化select查询。
public List<Order> getallorders(List<Branch> BranchNumber,String startDate,String endDate) throws SQLException {
List<Order> orders = new ArrayList<Order>();
try {
StringBuilder sb = new StringBuilder();
sb.append("SELECT ORDER_NUMBER as ordernumber,SERVICE as service"
+ "FROM ORDER WHERE "
+ "BRANCH IN(");
sb.append(getWildCards(BranchNumber.size())).append(")");
sb.append("AND ORDERDATE BETWEEN ? and ? WITH UR");
String query = sb.toString();
PreparedStatement statement =
connection.prepareStatement(query);
for(int i=0 ; i<BranchNumber.size() ;i++)
{
statement.setInt(i+1,BranchNumber.get(i).getBranch());
}
ResultSet resultSet = statement.executeQuery();
{
while (resultSet .next()) {
Order order1 = new Order();
order1.setOrdernumber(resultSet.getInt("ordernumber"));
orders.add(order1);
}
}
}
catch (SQLException e) {
e.printStackTrace();
}
return orders;
}
有人可以解释一下我在这里做错了什么以及我如何得到预期的预备陈述,下面是我记录的日志和错误信息中的格式化查询,
SELECT ORDER_NUMBER as ordernumber,SERVICE_TYPE as service FROM .ORDER WHERE
BRANCH_NUMBER IN(?) + AND ORDERDATE BETWEEN ? AND ? WITH UR
com.ibm.db2.jcc.am.SqlSyntaxErrorException: DB2 SQL Error: SQLCODE=-104,
SQLSTATE=42601, SQLERRMC=ORDER DATE BETWEEN ? AND;H_NUMBER IN(?) + AND;
<order_siblings_by>, DRIVER=3.63.75
at com.ibm.db2.jcc.am.fd.a(fd.java:679)
答案 0 :(得分:2)
?
中的每个prepareStatement
都应分配一个值。以下是here采用的示例:
String updateString =
"update " + dbName + ".COFFEES " +
"set SALES = ? where COF_NAME = ?";
PreparedStatement updateSales = con.prepareStatement(updateString);
updateSales.setInt(1, 500); //set value to first `?`
updateSales.setString(2, "roasted"); //set value to second `?`