Home > Database > Mysql Tutorial > Why Am I Getting \'Error Code: 1062. Duplicate entry \'1\' for key \'PRIMARY\'\' When Inserting Data?

Why Am I Getting \'Error Code: 1062. Duplicate entry \'1\' for key \'PRIMARY\'\' When Inserting Data?

DDD
Release: 2024-10-31 08:01:01
Original
907 people have browsed it

Why Am I Getting

Duplicate Primary Key Error: Resolving "Error Code: 1062. Duplicate entry '1' for key 'PRIMARY'"

When attempting to insert data into a table, you may encounter the error message "Error Code: 1062. Duplicate entry '1' for key 'PRIMARY.'" This error signifies that you are trying to insert a duplicate value into a column that is defined as a primary key.

In your case, the problem lies within the table PROGETTO.UFFICIO-INFORMAZIONI. The primary key for this table is defined as ID. You have explicitly specified the value of ID as 1 in your INSERT statement:

INSERT INTO `PROGETTO`.`UFFICIO-INFORMAZIONI` (`ID`, `viale`, `num_civico`, ...) 
VALUES (1, 'Viale Cogel ', '120', ...)
Copy after login

However, this value already exists in the table. As primary keys are unique for each record, you cannot insert a duplicate value.

Solution: Use Auto-Increment

The recommended solution to avoid duplicate primary key errors is to use auto-increment for the ID column. This means the database will automatically generate unique values for the ID column during insertion. To enable auto-increment, modify the table definition as follows:

CREATE TABLE IF NOT EXISTS `PROGETTO`.`UFFICIO-INFORMAZIONI` (
  `ID` INT(11) NOT NULL AUTO_INCREMENT,
  `viale` VARCHAR(45) NULL,
  ...
);
Copy after login

Once you have enabled auto-increment, you can omit the ID column in your INSERT statements:

INSERT INTO `PROGETTO`.`UFFICIO-INFORMAZIONI` (`viale`, `num_civico`, ...) 
VALUES ('Viale Cogel ', '120', ...)
Copy after login

By using auto-increment, the database will automatically assign a unique value to the ID column, ensuring that no duplicate key errors occur.

The above is the detailed content of Why Am I Getting 'Error Code: 1062. Duplicate entry '1' for key 'PRIMARY'' When Inserting Data?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template