views:

134

answers:

2

I have the following Java code:

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();

Whenever I run the above code, it throws an exception on line 2 (where the PreparedStatement is declared):

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

Does anyone have any suggestions about what I am doing wrong? Thanks!

A: 

Looks like the PreparedStatement class only supports SQL "IN" parameterized lists. Looks like you want to change it to using the prepareCall function instead:

CallableStatement stmt = conn.prepareCall(query);

And CallableStatement extends PreparedStatement so it's really easy to make the change.

Edit: Why the down votes? Why not leave a comment?

amphetamachine
A: 

You may try this

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

or

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

anyway your code is working perfectly for me;
Are you sure there are no special characters in your String?
What are the MySQL and driver version being used?
Is this the correct code?

Carlos Heuberger