preparedStatement语法错误

bry*_*bee 9 java mysql prepared-statement

我最近遇到了Java PreparedStatements的这个问题.我有以下代码:

String selectSql1
        = "SELECT `value` FROM `sampling_numbers` WHERE `value` < (?)" ;
    ResultSet rs1 = con.select1(selectSql1,randNum);
Run Code Online (Sandbox Code Playgroud)

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,它不断抛出此错误:

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)
Run Code Online (Sandbox Code Playgroud)

当我做天真的做法时,这个问题不会发生......" value < " + randNum但我想这样做.

任何帮助深表感谢.

UPDATE

我尝试了社区的各种建议,比如

String selectSql1
        = "SELECT `value` FROM `sampling_numbers` WHERE value < ?" ;

String selectSql1
        = "SELECT value FROM sampling_numbers WHERE value < ?" ;
Run Code Online (Sandbox Code Playgroud)

仍然出现错误消息.

Ell*_*sch 18

您的问题的解决方案实际上非常简单,当您要调用PreparedStatement.executeQuery()时,您正在调用Statement.executeQuery(String ) -

this.stmt = con.prepareStatement(sql); // Prepares the Statement.
stmt.setInt(1, randNum);               // Binds the parameter.
// return this.stmt.executeQuery(sql); // calls Statement#executeQuery
return this.stmt.executeQuery();       // calls your set-up PreparedStatement
Run Code Online (Sandbox Code Playgroud)