简体   繁体   中英

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?

Simply use

ps.executeQuery();

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

use this query :-

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

and simply use

ps.executeQuery();

我认为在准备查询时,这是语法问题,请尝试使用该语法。...string query2 =“ SELECT lname FROM school_student WHERE sid = + variablename + ORDER BY sid;”

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM