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', ...)
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, ... );
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', ...)
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!