Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

right syntax to use near '?'

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

like image 753
somebody Avatar asked Dec 20 '22 13:12

somebody


2 Answers

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).

like image 158
M A Avatar answered Jan 02 '23 09:01

M A


ResultSet resultPerson = statement.executeQuery(searchPerson);

should be

ResultSet resultPerson = statement.executeQuery();
like image 23
Felix Avatar answered Jan 02 '23 08:01

Felix