MYSQL Exception in prepared statement to use the right syntax near '?'

时间:2015-05-04 19:47:22

标签: mysql jdbc

I have written the following code. But I am getting the MySQL Exception to use the right syntax near '?'. Can you help me to resolve this issue?

public static void inbox(String username) {
    String query_recipient = "SELECT user_id, first_name, last_name FROM user_info WHERE username = '" + username + "' ";
    String query = "SELECT sub, msg FROM message WHERE recipient = ?";
    Statement s = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    ResultSet rs1 = null;
    int userId = 0;

    try {
        s = Connect.con.createStatement();
        rs = s.executeQuery(query_recipient);
        rs.next();
        userId = rs.getInt("user_id");

        ps = Connect.con.prepareStatement(query);
        ps.setInt(1, userId);

        rs1 = ps.executeQuery(query);

        while (rs1.next()) {
            System.out.println(rs1.getString("sub"));
            System.out.println(rs1.getString("msg"));
        }

    } catch (SQLException ex) {
        Logger.getLogger(UserBAL.class.getName()).log(Level.SEVERE, null, ex);
    } //end catch
} //end inbox()

Edit: This is the error message

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(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
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:4120)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4052)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2503)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2664)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2788)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2738)
at com.mysql.jdbc.StatementImpl.executeQuery(StatementImpl.java:1617)
at msg_pkg.MsgBAL.inbox(MsgBAL.java:82)
at msg_pkg.MsgBAL.main(MsgBAL.java:116)

1 个答案:

答案 0 :(得分:0)

无需query作为参数传递给

rs1 = ps.executeQuery(query);

所以就把它取下来

rs1 = ps.executeQuery();