简体   繁体   中英

Syntax error in Prepared statement while inserting into db

Hi I am trying insert data into the database using prepared statement but I am getting syntax error could u please help

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();

}

here is the error message

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

I found the answer :)

Use preparedStatement.execute() instead of executeUpdate(sql). You have already set the sql and params - the new setting in executeUpdate(sql) overrides the bind.

You should change the statement to list the columns explicitly, and drop NULL from the list of values.

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

This way your insert statement is no longer dependent on the order of columns in your users table, and is also immune to addition of columns to the table.

Note that although this design is probably OK for a toy or an education system, but in a real production system storing password in a table is very dangerous. Storing confirm_password is rather unusual, too: normally your system checks that password is the same as confirm_password , and then inserts a salted password hash and a salt into the table.

Just a guess, not I'm not certain. But if one of the fields is autoincrement, then I don't think you need to insert it. Try taking out that NULL....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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