我正在尝试使用java mysql库,但是我在使用预准备语句时遇到了问题。我不确定我错过了什么。以下是我在尝试使用预准备语句时遇到的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);
我收到以下错误:
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
如果我执行“campaign_id =”+ campaignId,它是有效的,但SQL注入等待发生。
答案 0 :(得分:2)
试试这个
ResultSet rs = preparedStatement.executeQuery();
答案 1 :(得分:0)
PreparedStatement
方法executeQuery()
本身返回一个ResultSet对象
因此将其分配给ResultSet
对象
ResultSet rs = preparedStatement.executeQuery();
错误:
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
发生此错误是因为
时ResultSet rs = st.executeQuery(query);
此语句执行它在?
运算符中找不到任何值。
所以你的查询仍然是"SELECT id, clicks FROM mailer.links WHERE campaign_id=?";
,这会引发MySQL语法异常。