1

我收到异常,因为 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)
4

3 回答 3

6

您的代码中有一个错误:

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
于 2013-10-19T05:07:44.003 回答
0

你的 SQL 应该只是

SELECT * FROM patient WHERE patient._ID = ?

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

于 2013-10-19T05:06:05.793 回答
0

改变这个String sql = "SELECT * FROM patient.patient WHERE patient._ID=?";

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

于 2013-10-19T05:07:37.527 回答