正确的语法在'?'附近使用

时间:2014-07-23 18:14:38

标签: java mysql sql jdbc prepared-statement

我有一个Java代码:

String searchPerson = "select * from persons where surname like ? and name like ?";
//connect to DB
PreparedStatement statement = connect.prepareStatement(searchPerson);
statement.setString(1,"%"+ surname + "%");
statement.setString(2, "%" + name + "%");
ResultSet resultPerson = statement.executeQuery(searchPerson);
//..code

然后我有SQLException:

  

您的SQL语法有错误;查看与您的MySQL服务器版本对应的手册,以便在'附近使用正确的语法?'

3 个答案:

答案 0 :(得分:8)

您应该执行没有参数的PrepareStatement,如下所示:

statement.executeQuery()

使用executeQuery参数调用String将按原样执行提供的查询(不带绑定参数)。

答案 1 :(得分:1)

ResultSet resultPerson = statement.executeQuery(searchPerson);

应该是

ResultSet resultPerson = statement.executeQuery();

答案 2 :(得分:-2)

尝试使用statement.setString(1,"'%"+ surname + "%'");