繁体   English   中英

插入数据库时​​,Prepared语句中的语法错误

[英]Syntax error in Prepared statement while inserting into db

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

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

我找到了答案:)

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

您应该更改该语句以显式列出列,然后从值列表中删除NULL

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM