使用 Java 的 PreparedStatement 进行 select 查询时出现 SQL 异常
Getting SQL Exception while using Java's PreparedStatement for select query
我已经通过复制粘贴手动输入查询,并且运行正常。当我对 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();
}
下面是我正在使用的table:
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
不要对标记“?”使用引号(单引号和双引号)。而不是:
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 = ? ";
我已经通过复制粘贴手动输入查询,并且运行正常。当我对 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();
}
下面是我正在使用的table:
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
不要对标记“?”使用引号(单引号和双引号)。而不是:
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 = ? ";