使用Java的PreparedStatement进行选择查询时获取SQL异常

时间:2017-03-26 03:36:41

标签: java db2 sqlexception

我已手动输入查询并通过复制粘贴,并且运行正常。当我将查询放入PreparedStatement对象时,我收到一个错误:

com.ibm.db2.jcc.am.SqlSyntaxErrorException: [jcc][10145][10844][4.22.29] Invalid parameter 1: Parameter index is out of range. ERRORCODE=-4461, SQLSTATE=42815

我已经阅读了PreparedStatement对象的JavaDoc,但是我的想法很新鲜。我的其他查询相同(但使用int而不是String)工作正常。有什么想法吗?

代码片段:

      String queryText = "";
      PreparedStatement querySt = null; 
      ResultSet answers = null; 


      queryText = "SELECT title, year, language, weight FROM yrb_book WHERE title = '?' AND cat = '?' ";

      try 
      {
          querySt = DbConn.prepareStatement(queryText);
      } 
      catch(SQLException e) 
      {
          System.out.println(e);
          System.exit(0);
      }

      // Execute the query.
      try 
      {
          querySt.setString(1, title);
          querySt.setString(2, category);
          answers = querySt.executeQuery();
      }

以下是我正在使用的表格: create table yrb_book ( title varchar(25) not null, year smallint not null, language varchar(10), cat varchar(10) not null, weight smallint not null, constraint yrb_book_pk primary key (title, year), constraint yrb_book_fk_cat foreign key (cat) references yrb_category, constraint yrb_book_weight check (weight > 0) );

我研究了这个答案30分钟,但看不出它如何适用于我的情况。 Getting SQL Exception while using prepared statement for select query

1 个答案:

答案 0 :(得分:3)

不要为令牌“?”使用引号(单引号和双引号)。而不是:

queryText = "SELECT title, year, language, weight FROM yrb_book WHERE title = '?' AND cat = '?' ";

使用:

queryText = "SELECT title, year, language, weight FROM yrb_book WHERE title = ? AND cat = ? ";