[英]Java MYSQL Prepared Statement Error: Check syntax to use near '?' at line 1
I am trying to use the java mysql library but I am having issues using a prepared statement. 我正在尝试使用Java mysql库,但是在使用准备好的语句时遇到了问题。 I am not sure what I am missing. 我不确定我缺少什么。 Below is what I have with the MYSQL error attempting to use the prepared statement. 以下是尝试使用预处理语句时遇到的MYSQL错误。
String query = "SELECT id, clicks FROM mailer.links WHERE campaign_id=?";
try {
preparedStatement = connect.prepareStatement(query);
preparedStatement.setInt(1, campaignId);
preparedStatement.execute();
Statement st = connect.createStatement();
// execute the query, and get a java resultset
ResultSet rs = st.executeQuery(query);
I am getting the following error: 我收到以下错误:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:
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
It works if I do "campaign_id=" + campaignId , but is a SQL injection waiting to happen. 如果我执行“ campaign_id =” + campaignId,它会起作用,但是正在等待SQL注入。
尝试这个
ResultSet rs = preparedStatement.executeQuery();
PreparedStatement
method executeQuery()
itself returns a ResultSet object PreparedStatement
方法executeQuery()
本身返回ResultSet对象
So assign this to a ResultSet
object 因此,将其分配给ResultSet
对象
ResultSet rs = preparedStatement.executeQuery();
Error: 错误:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:
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
And this error happens because When 发生此错误是因为
ResultSet rs = st.executeQuery(query);
This statement executes it can't find any value in ?
该语句执行后在中找不到任何值?
operator. 运营商。 so your query remains this "SELECT id, clicks FROM mailer.links WHERE campaign_id=?";
因此您的查询仍然是"SELECT id, clicks FROM mailer.links WHERE campaign_id=?";
and this throws a MySQL Syntax Exception. 这会引发MySQL语法异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.