一尘不染

prepareStatement语法错误

mysql

我最近在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 < ?" ;

仍然出现错误信息。


阅读 297

收藏
2020-05-17

共1个答案

一尘不染

解决问题的方法实际上非常简单,当您要调用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
2020-05-17