2

嗨,我正在尝试使用准备好的语句将数据插入数据库,但出现语法错误,请您帮忙

public boolean SignUp(String last_name, String first_name,String email, String password,String confirm_password,String phone){



        Connect connect = new Connect();
        Connection conn = connect.Connection();

        java.sql.PreparedStatement preparedStatement = null;
        //NULL is the column for auto increment
        String insertQuery = "INSERT INTO users VALUES (NULL, ?, ?, ?, ?, ?, ?)";
        preparedStatement = conn.prepareStatement(insertQuery);
        preparedStatement.setString(1, last_name);
        preparedStatement.setString(2, first_name);
        preparedStatement.setString(3, email);
        preparedStatement.setString(4, password);
        preparedStatement.setString(5, confirm_password);
        preparedStatement.setString(6, phone);

        int rs = preparedStatement.executeUpdate(insertQuery);

        conn.close();

}

这是错误消息

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
4

3 回答 3

5

我找到了答案:)

使用preparedStatement.execute() 而不是executeUpdate(sql)。您已经设置了 sql 和参数 - executeUpdate(sql) 中的新设置覆盖了绑定。

于 2012-10-09T23:29:04.103 回答
2

您应该更改语句以明确列出列,并NULL从值列表中删除。

String insertQuery = "INSERT INTO users"
+  " (last_name, first_name, email, password, confirm_password, phone)"
+  " VALUES(?,?,?,?,?,?)";

这样,您的插入语句不再依赖于users表中列的顺序,并且也不受向表中添加列的影响。

请注意,虽然这种设计对于玩具或教育系统来说可能没问题,但在实际生产系统中,将密码存储在表格中是非常危险的。存储confirm_password也很不寻常:通常您的系统检查它password是否与 相同confirm_password,然后将加盐密码哈希和盐插入表中。

于 2012-07-26T17:55:20.353 回答
0

只是猜测,不是我不确定。但是,如果其中一个字段是自动增量的,那么我认为您不需要插入它。尝试取出那个NULL....

于 2012-07-26T17:57:33.807 回答