PreparedStatement with parameterised where子句在select语句中抛出异常

时间:2013-10-19 05:04:03

标签: java mysql jdbc prepared-statement

我收到异常,因为SQLException显示语法有问题并检查手册是否相同。

我的java代码如下。

PreparedStatement pst;
String sql ="SELECT * FROM patient.medicine where _id=?";
pst = cn.prepareStatement(sql);
    pst.setInt(1, 1);
ResultSet rs = pst.executeQuery(sql);

如果我通过追加持有id值的变量来执行此操作,那么一切正常。

*SELECT * FROM patient.medicine where _name=?*
Oct 19, 2013 11:15:46 AM com.seed.entity.Patient getData
SEVERE: null
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 '?' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1053)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4096)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4028)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2490)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2651)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2728)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2678)
at com.mysql.jdbc.StatementImpl.executeQuery(StatementImpl.java:1612)
at com.seed.entity.Patient.getData(Patient.java:257)
at com.seed.entity.Patient.main(Patient.java:360)

3 个答案:

答案 0 :(得分:5)

您的代码中有一个错误:

PreparedStatement pst;
String sql ="SELECT * FROM patient.patient P WHERE P._ID = ?";
pst = cn.prepareStatement(sql);
pst.setInt(1, 1);
ResultSet rs = pst.executeQuery(); // without arguments

答案 1 :(得分:0)

你的SQL应该只是

SELECT * FROM patient WHERE patient._ID = ?

表名patient.patient似乎不正确,因为该列称为patient._ID

答案 2 :(得分:0)

更改此String sql = "SELECT * FROM patient.patient WHERE patient._ID=?";

String sql = "SELECT * FROM patient WHERE patient._ID=?";