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
  • 90,369
  • 161
  • 124
  • 175
somebody
  • 1,027
  • 4
  • 14
  • 30
  • @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

12

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
  • 69,673
  • 13
  • 131
  • 165
1
ResultSet resultPerson = statement.executeQuery(searchPerson);

should be

ResultSet resultPerson = statement.executeQuery();
user247702
  • 22,915
  • 14
  • 108
  • 152
Felix
  • 11
  • 1
-2

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

user247702
  • 22,915
  • 14
  • 108
  • 152
user3510364
  • 118
  • 3