【问题标题】:Getting SQL Exception while using Java's PreparedStatement for select query使用 Java 的 PreparedStatement 进行选择查询时出现 SQL 异常
【发布时间】:2017-03-26 03:36:41
【问题描述】:

我已经手动输入查询并通过复制粘贴,它运行良好。当我对 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)工作正常。有什么想法吗?

一个sn-p的代码:

      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

【问题讨论】:

    标签: java db2 sqlexception


    【解决方案1】:

    不要对标记“?”使用引号(单引号和双引号)。而不是:

    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 = ? ";
    

    【讨论】:

    • @ jplc 你需要单引号,否则它会变成一个错误的 db2 查询。我正在尝试更多这样的方式:string temp = "'"+title+"'";
    • @Mike 您是否执行了建议的新查询。 Java SQL API (PreparedStatement) 为您完成这项工作。如果您收到新错误,请发布。
    • 你是对的,我错了。你的建议解决了我的问题。谢谢你的建议,我真的很感激!在自己替换? 时,Java 确实将' 添加到字符串中。再次感谢。
    猜你喜欢
    • 2011-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-01
    • 1970-01-01
    • 2016-01-27
    • 2015-05-21
    • 1970-01-01
    相关资源
    最近更新 更多