【问题标题】:how PreparedStatement.setString inside of the loop works?循环内的 PreparedStatement.setString 是如何工作的?
【发布时间】:2020-10-10 02:17:06
【问题描述】:

我的 url 中有一个查询参数列表,我想在我的 java web 服务中使用它们来对表运行查询

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

}

我总是在 getStatement.setString(1, value); 中使用 1 的原因是,我认为在每次迭代中,一个 ? 被替换为该值,但最后我得到一些异常说 java.sql.SQLException: IN or OUT位置 2 处缺少参数。

有谁知道我在这里做错了什么?

【问题讨论】:

  • getStatement.setString(1, value); 更改为getStatement.setString(i+1, value);
  • 通过您的编辑,您使您的问题无效,并使现有答案错误。我已回滚您的编辑。

标签: java jdbc


【解决方案1】:

您不能每次都在getStatement.setString() 中使用1。您还必须增加该数字才能将第二个 ? 替换为实际值。

由于您一直只传递1,然后尝试执行查询,Java 表示当您获得java.sql.SQLException: IN or OUT param missing at position 2 时没有为第二个? 提供值。

getStatement.setString(i+1, value) 替换getStatement.setString(1, value) 应该可以解决问题。但是您必须确保sortedQueryParamsValue 中的元素数等于getStatement 查询中? 的数量。

编辑:在@Eritrean 发表评论后将setString(i,value) 更正为setString(i+1,value)

【讨论】:

  • 谢谢@Meet K。但是当我按照你说的做时,结果是空的。
  • 调试你的程序。通过添加断点提取在行 getStatement.executeQuery() 生成的查询。然后在数据库服务器上手动运行这个查询,验证查询是否正确,是否真的返回了任何结果。
  • 是的,它返回值。我找不到查看 getStatement.executeQuery() 运行的查询是什么的方法。我只能知道我的查询是什么并替换 ?使用值并在我的数据库上运行它并返回值
  • 应该是setString(i+1, value),因为准备好的语句索引从 1 开始,而不是 0
  • @WaterfrVilla 请接受答案并关闭问题,因为您的原始问题已得到解决。并学习如何调试你的代码,它会对你有很大帮助。 This article 应该可以帮助您入门。
【解决方案2】:

问题是通过 URL 将查询参数传递给其余 API 可能会有一些空格,而这些空格会导致查询返回空, 我将把 1 改为 i+1 只是为了不误导读者

【讨论】:

  • 问题是你有1而不是i+1。空白与它无关,尤其是“主要是空白”。 URL 和 REST API 与它几乎没有任何关系,因为它们都没有出现在您的问题中。
猜你喜欢
  • 1970-01-01
  • 2015-02-03
  • 1970-01-01
  • 2014-03-15
  • 2012-05-17
  • 2022-01-03
  • 2013-03-30
相关资源
最近更新 更多