4

I have a Java-code:

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

Then I have SQLException:

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 '?'

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
somebody
  • 1,077
  • 5
  • 14
  • 32
  • @AdamYost: no he doesn't, that's the whole point of ? placeholder – mvp Jul 23 '14 at 18:17
  • than I have an error to set String: `code` statement.setString(1,"%"+ surname + "%"); statement.setString(2, "%" + name + "%"); `code` – somebody Jul 23 '14 at 18:21
  • I guess this is one of mysql bugs. Change you statement to `like '%' || ? || '%'` and use `.setString(1, surname)` and it should work – mvp Jul 23 '14 at 18:26
  • @mvp than I have: 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 '? || '%'' – somebody Jul 23 '14 at 18:29

3 Answers3

14

You should execute the PrepareStatement with no parameters as follows:

statement.executeQuery()

Calling executeQuery with a String parameter will execute the provided query as is (without the bound parameters).

M A
  • 71,713
  • 13
  • 134
  • 174
1
ResultSet resultPerson = statement.executeQuery(searchPerson);

should be

ResultSet resultPerson = statement.executeQuery();
user247702
  • 23,641
  • 15
  • 110
  • 157
Felix
  • 11
  • 1
-2

Try with statement.setString(1,"'%"+ surname + "%'");

user247702
  • 23,641
  • 15
  • 110
  • 157
user3510364
  • 138
  • 3