【问题标题】:Parameter not set error in Prepared statementPrepared 语句中的参数未设置错误
【发布时间】:2015-08-28 12:37:10
【问题描述】:

我正在尝试在 JDBC 中执行准备好的语句,每次执行时都会收到错误消息“未设置参数”。 我反复尝试检查未设置的参数 - 但我只有一个。这让我相信这是我的另一个愚蠢错误。

如果您能指出这一点,我将不胜感激

public book search(String key){
        book temp = null;

        try {
            String stmt = "SELECT BookID, Title, Author, Media, Available FROM BOOK WHERE Title LIKE ?;"; 
            connection = DatabaseConnection(); 
            PreparedStatement preparedStmt = connection.prepareStatement(stmt); 
            System.out.println(key);
            preparedStmt.setObject(1, key);//the name
            statement = connection.prepareStatement(stmt); //Using Prepared Statements prepare the query

            resultSet = statement.executeQuery(); //Execute the query



            while (resultSet.next()) {

                int bookID = resultSet.getInt("BookID");//Get the userName
                String title = resultSet.getString("Title"); //Get the score
                String author = resultSet.getString("Author"); //Get the score
                String media = resultSet.getString("Media"); //Get the score
                boolean available = resultSet.getBoolean("Available"); //Get the score

                temp = new book(title,author,media,available,bookID);


            }
            connection.close(); //close connection


        } catch (SQLException e) {
            System.err.println("Got an exception!");
            System.err.println(e.getMessage());
        }



        return temp;


    }

【问题讨论】:

  • 不相关但是:最好使用对应实际数据类型的setXXX()方法。 setObject() 可能并不总是按预期工作。所以在你的情况下使用setString(1, key) 会更可靠。

标签: java sql jdbc


【解决方案1】:

您调用了两次prepareStatement,在第一次设置参数,然后在第二次调用executeQuery

不清楚你在哪里声明 statementresultSet,但你想要:

PreparedStatement preparedStmt = connection.prepareStatement(stmt); 
preparedStmt.setString(1, key);
ResultSet resultSet = preparedStmt.executeQuery();

请注意,我已将 resultSet 设为局部变量 - 你真的不希望它成为一个字段......你的 temp 变量也没有理由,因为你可以直接从 @987654328 返回@ 环形。 (我也将代码更改为使用setString 而不是setObject...)

您应该使用 try-with-resources 语句来自动关闭语句和结果集...)

【讨论】:

  • 天哪,真不敢相信我错过了!谢谢
  • 如果直接从while循环返回,那么绝对应该使用try-with-resources,以便在退出方法时正确关闭StatementConnection
猜你喜欢
  • 2012-03-27
  • 1970-01-01
  • 2018-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多