我最近在使用Java PreparedStatements时遇到了这个问题。我有以下的代码:
String selectSql1
= "SELECT `value` FROM `sampling_numbers` WHERE `value` < (?)" ;
ResultSet rs1 = con.select1(selectSql1,randNum);
select1
方法所在的位置。
public ResultSet select1(String sql, int randNum) {
try {
this.stmt = con.prepareStatement(sql);
stmt.setInt(1, randNum);
return this.stmt.executeQuery(sql);
} catch (SQLException e) {
e.printStackTrace();
return 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(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
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:1054)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4237)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4169)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2617)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2778)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2828)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2777)
at com.mysql.jdbc.StatementImpl.executeQuery(StatementImpl.java:1651)
at util.P_DBCon.select1(P_DBCon.java:59)
at app.RandomNumberGenerator.main(RandomNumberGenerator.java:60)
Exception in thread "main" java.lang.NullPointerException
at app.RandomNumberGenerator.main(RandomNumberGenerator.java:64)
当我采用“...value < " + randNum
”这种天真的方式时,不会出现这个问题,但是我想采用这种方式。
非常感谢任何帮助。
更新
我尝试了社区提供的各种建议,比如
String selectSql1
= "SELECT `value` FROM `sampling_numbers` WHERE value < ?" ;
String selectSql1
= "SELECT value FROM sampling_numbers WHERE value < ?" ;
仍然出现错误信息。