zProgrammer
zProgrammer

Reputation: 739

Prepared statements with MySQL?

I am having some trouble with, what I believe to by syntax, for prepared statements.

I have the following code

String query2="SELECT lname FROM school_student WHERE sid = ? ORDER BY sid;";

PreparedStatement ps = cn.prepareStatement(query2);
ps.setInt(1, 3);
ResultSet rs = ps.executeQuery(query2);

The problem I am having is that I am getting this error message:

com.mysql.jdbc.exceptions.jdbc4.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 '? ORDER BY sid' at line 1

However, when I substitute the "?" in my query for a 3, the query works fine with no error and gives me what I want. There seems to be something wrong with how I am setting the value of the "?" in my query? Am I using the wrong syntax?

Upvotes: 0

Views: 336

Answers (3)

Rana
Rana

Reputation: 324

use this query :-

String query2 = "SELECT lname FROM school_student WHERE sid = "+attribute+" ORDER BY sid;";

and simply use

ps.executeQuery();

Upvotes: 2

Tech fun
Tech fun

Reputation: 1

I think their is syntax problem while preparing query try this one... String query2="SELECT lname FROM school_student WHERE sid = +variablename+ ORDER BY sid;"

Upvotes: -1

JB Nizet
JB Nizet

Reputation: 691625

Simply use

ps.executeQuery();

(i.e. use the overloaded executeQuery() method which doesn't take any argument). You already passed the query when preparing the statement.

Upvotes: 7

Related Questions