简体   繁体   English

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

[英]Getting SQL Exception while using Java's PreparedStatement for select query

I have entered the query manually and by copy pasting, and it runs fine. 我已经手动输入查询并通过复制粘贴输入了查询,它运行良好。 When I make the query into a PreparedStatement Object I get an error: 当我对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

I have read the JavaDoc for PreparedStatement objects but am fresh out of ideas. 我已经阅读了JavaDoc for PreparedStatement对象,但是对这些想法不屑一顾。 My other queries that are identical (but use int instead of String) work fine. 我的其他相同查询(但使用int代替String)可以正常工作。 Any thoughts? 有什么想法吗?

A snippet of the code: 一段代码:

      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();
      }

Below is the table I am working with: 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) ); 下面是我正在使用的表: 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) );

I studied this answer for 30 minutes, but cannot see how it can apply in my case. 我研究了这个答案30分钟,但看不到如何将其应用于我的案例。 Getting SQL Exception while using prepared statement for select query 使用准备好的语句进行选择查询时获取SQL异常

Don't use quotes (single and double) for token "?". 不要在标记“?”中使用引号(单引号和双引号)。 Instead of: 代替:

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

use: 采用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM