Java 循环内部的PreparedStatement.setString是如何工作的?
我的url中有一个查询参数列表,我想在JavaWeb服务中使用这些参数来运行表上的查询Java 循环内部的PreparedStatement.setString是如何工作的?,java,jdbc,Java,Jdbc,我的url中有一个查询参数列表,我想在JavaWeb服务中使用这些参数来运行表上的查询 public Set<Result> getResult(String query, List<String> sortedQueryParamsValue) { Connection connection = getConnection();//jdbc connection //query is some thing like: select * from tab
public Set<Result> getResult(String query, List<String> sortedQueryParamsValue) {
Connection connection = getConnection();//jdbc connection
//query is some thing like: select * from table A where status = ? and Id = ?
try (PreparedStatement getStatement = connection.prepareStatement(query)) {
for (int i = 0; i <sortedQueryParamKeys.size(); i++) {// sortedQueryParamsValue length is matching the number of values I need for the query and the order matches the order I am expecting
String value = sortedQueryParamsValue.get(i);
getStatement.setString(1, value);
}
try (ResultSet rs = getStatement.executeQuery()) {
while (rs.next()) {
//add to the list of results
}
}
//return the resultset
}
public Set getResult(字符串查询、列表排序查询参数值){
Connection Connection=getConnection();//jdbc连接
//查询类似于:从表A中选择*,其中status=?和Id=?
try(PreparedStatement getStatement=connection.prepareStatement(query)){
对于(int i=0;i您不能每次在getStatement.setString()
中使用1
。您也必须增加该数字,以便用实际值替换第二个?
由于您一直只传递1
,然后尝试执行查询,因此当您在位置2处获得Java.sql.SQLException:IN或OUT参数时,Java表示没有为第二个?
提供值
将getStatement.setString(1,value)
替换为getStatement.setString(i+1,value)
应该可以。但是您必须确保sortedQueryParamsValue
中的元素数等于getStatement
查询中的?
编辑:在@Eritrean的评论之后,将setString(i,value)
更正为setString(i+1,value)
。问题是通过URL将查询参数传递给rest API可能会有一些空格,这些空格会导致查询返回空,
我将把1改为I+1,以避免误导读者谢谢@Meet K。但当我按照你说的做时,结果返回为空。调试你的程序。提取在第getStatement.executeQuery()行生成的查询
通过添加断点。然后在数据库服务器上手动运行此查询,并验证查询是否正确,以及它是否实际返回任何结果。是,它返回值。我找不到方法查看getStatement.executeQuery()执行的查询是什么正在运行。我只能知道我的查询是什么,用值替换?并在我的数据库上运行它,它返回的值应该是setString(I+1,value)
因为准备好的语句索引从1开始,而不是从1开始0@WaterfrVilla由于原始问题已经解决,请接受答案并关闭问题。学习如何调试代码,这将对您有很大帮助。应该可以帮助您开始。将getStatement.setString(1,value);
更改为getStatement.setString(i+1,value)
您的编辑使您的问题无效,并使现有答案出错。我已回滚您的编辑。问题是您使用的是1
而不是I+1
。空白与此无关,尤其是“大部分空白”。URL和REST API与此无关,因为它们在你的问题。