简体   繁体   中英

Inserting into database with auto increment

I need to store some values into my table using prepared statements.

I have a column in my table called id, and it is set to auto increment. I do not need any input from the user for this column.

The other values are all gotten from the user.

Edit: There are 2 IDs. One from the user and one that is auto generated from the database. The one automatically generated by the database is the primary key.

Am I doing this right?

Thanks.

Prepared Statement:

DELIMITER $$

CREATE DEFINER=`root`@`localhost` PROCEDURE `insert_details`(IN id varchar(45),IN username varchar(45),IN name varchar(45)) 

BEGIN insert into details (id,username,name) values (id ,username,name);

END

Code:

PreparedStatement preparedStatement = connect.prepareStatement("CALL INSERT_DETAILS(?,?,?)");
preparedStatement.setLong(1, userID);
preparedStatement.setString(2, username);
preparedStatement.setString(3, name);

preparedStatement .executeUpdate();

You can simply omit auto-generated field from the prepared statement as MySQL will set this value for you. In your example, your parameter names are colliding with table attribute names. The convention that I follow is to prefix parameter names with a p_ or similar name mangling.

The prepared statement should look more like the following:

DELIMITER $$
CREATE
  DEFINER=`root`@`localhost`
PROCEDURE `insert_details`(
  IN p_user_id VARCHAR(45),
  IN p_username VARCHAR(45),
  IN p_name VARCHAR(45))
BEGIN
  INSERT
    INTO details(id, username, name)
    VALUES (p_user_id, p_username, p_name);
END $$

Remove the id field from your prepared statement.

Because it will conflict the field data so problem may occur.

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