在executeUpdate中的预准备语句中抛出异常

时间:2014-07-30 12:34:38

标签: java sql

MySQLdb mySQLdb =new MySQLdb();
    query="INSERT  INTO user(username,password,firstname,email) VALUES (?,?,?,?)";
    System.out.println(user.getUsername()+"  "+user.getPassword()+" "+user.getName()+" "+user.getEmail());
    connection= mySQLdb.getConnection();
    try {

        preparedStatement=connection.prepareStatement(query);

        preparedStatement.setString(1, user.getUsername());
        preparedStatement.setString(2, user.getPassword());
        preparedStatement.setString(3, user.getName());
        preparedStatement.setString(4, user.getEmail());
        preparedStatement.executeUpdate(query);//--->throws exception here
        //System.out.println("101");
        return true;
    } catch (Exception e) {
        System.out.println(e.getMessage());
        //System.out.println("102");
        e.printStackTrace();
    }

ERRORMESSAGE:

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
java.sql.SQLException: 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 com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2928)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1571)

帮我解决这个问题

3 个答案:

答案 0 :(得分:3)

不带参数调用executeUpdate

preparedStatement.executeUpdate();

答案 1 :(得分:2)

您已经在

设置了查询参数
preparedStatement=connection.prepareStatement(query);
                                                ^Here

所以改为调用此

preparedStatement.executeUpdate(query);

删除executeUpdate();

中的查询参数

并将其作为

preparedStatement.executeUpdate();

答案 2 :(得分:0)

不传递executeUpdate()中的查询字符串 它将解决您的问题 因为当你传递参数时,它会调用Statement的executeUpdate()函数 (即)statement.excuteUpdate(Query);

对于PreparedStatement ---> preparedStatement.executeUpdate();