问题出在准备的语句参数,当向选择查询中注入单个参数时。

huangapple go评论71阅读模式
英文:

Issue with the Prepared Stetement Parameter when injecting Single Parameter in Select Query

问题

我正在尝试为选择查询创建预处理语句

String Select_Query = "select * from customers where customerNumber=?";
Connection connection = DriverManagersSQL.getDriverMangerInstance();
preparedStatement statement = connection.prepareStatement(Select_Query);
statement.setInt(1, 101);
ResultSet resultSet = statement.executeQuery(Select_Query);

但是我遇到了一个错误,如下所示:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?' at line 1

我在数据库中运行了这个查询,它正常工作,没有语法错误。每当我尝试使用单个筛选参数时,我总是遇到这个问题。对任何建议表示感谢。

谢谢

英文:

I am trying to create the prepared statement for the select query

String Select_Query = "select * from customers where customerNumber=? ";
Connection connection = DriverManagersSQL.getDriverMangerInstance();
preparedStatement statement = connection.prepareStatement(Select_Query);
statement.setInt(1, 101);
ResultSet resultSet = statement.executeQuery(Select_Query);

But I am having one error like this :

 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?' at line 1

I ran the query into the database and its working fine. There is no syntax error. This happens with me all the time when I try to use with single filtering parameter. Any suggestions will be appreciated.

Thanks

答案1

得分: 2

不要调用

statement.executeQuery(Select_Query)

你已经设置好了你的 PreparedStatement。它已经包含了你的 SQL 以及其中的参数。

只需要调用

statement.executeQuery()

即可。

executeQuery() 是 PreparedStatement 的一个方法,它将执行你之前提供的查询,并使用你已经设置的参数。

executeQuery(String) 是 Statement 的一个方法,它尝试执行你当前提供的查询。它不会使用你的参数,文档明确指出,如果你在 PreparedStatement 上调用此方法,将会导致 SQLException。

英文:

Don't call

statement.executeQuery(Select_Query)

You've already set up your PreparedStatement. It's already got your SQL and the parameters that go in it.

Just call

statement.executeQuery()

instead.

executeQuery() is a method of PreparedStatement that will perform the query you already gave it, using the parameters you have already set.

executeQuery(String) is a method of Statement which tries to execute the query you are giving it now. It does not use your parameters, and the docs specifically say that if you call this method on a PreparedStatement it will cause an SQLException.

huangapple
  • 本文由 发表于 2020年9月9日 05:06:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/63801561.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定