MySQL Error: Duplicate Entry for Primary Key
Error Code: 1062. Duplicate entry '1' for key 'PRIMARY'
Problem:
When attempting to insert a new row into the UFFICIO-INFORMAZIONI table, you receive an error that a duplicate entry exists for the primary key value '1'.
Explanation:
The primary key is a unique constraint on a column or set of columns in a table. It ensures that each row has a unique identifier. In your case, the ID column is defined as the primary key, which means that no two rows can have the same value for the ID column.
Cause:
The error is raised because you are trying to insert a new row with an ID value that already exists in the table. This violates the primary key constraint, as there cannot be two rows with the same primary key value.
Solution:
There are two possible solutions to this issue:
Example:
To use auto-incrementing in MySQL, modify the table creation statement as follows:
<code class="sql">CREATE TABLE IF NOT EXISTS `PROGETTO`.`UFFICIO-INFORMAZIONI` ( `ID` INT(11) NOT NULL AUTO_INCREMENT, `viale` VARCHAR(45) NULL , .....</code>
This will create an ID column that automatically increments for each new row inserted into the table. You can then omit the ID value when inserting new rows.
<code class="sql">INSERT INTO `PROGETTO`.`UFFICIO-INFORMAZIONI` (`viale`, `num_civico`, ...) VALUES ('Viale Cogel ', '120', ...)</code>
The above is the detailed content of Why am I getting a \'Duplicate Entry for Primary Key\' Error (Code 1062) in MySQL?. For more information, please follow other related articles on the PHP Chinese website!