PreparedStatement抛出MySQLSyntaxErrorException

时间:2010-05-11 15:24:40

标签: java mysql prepared-statement

我有以下Java代码:

String query = "Select 1 from myTable where name = ? and age = ?";
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setString(1, name);
stmt.setInt(2, age);
ResultSet rs = stmt.executeQuery();

每当我运行上面的代码时,它会在第2行抛出异常(声明PreparedStatement):

Error 0221202: SQLException = com.mysql.jdbc.exceptions.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 '? AND age = ?' at line 1

有没有人对我做错了什么有任何建议?谢谢!

2 个答案:

答案 0 :(得分:1)

你可以试试这个

String query = "Select 1 from myTable where `name` = ? and age = ?";

String query = "Select count(*) from myTable where `name` = ? and age = ?";  

无论如何,你的代码对我来说非常合适;
你确定你的字符串中没有特殊字符吗?
使用的MySQL和驱动程序版本是什么? 这是正确的代码吗?

答案 1 :(得分:-2)

看起来PreparedStatement类仅支持SQL“IN”参数化列表。您希望将其更改为使用prepareCall功能:

CallableStatement stmt = conn.prepareCall(query);

CallableStatement延伸PreparedStatement,因此进行更改非常容易。

相关问题