Error with inserting into mysql database - mysql

I am using cfwheels (coldfusion orm framework).
I recently moved some data from my previous host to a new one. Now I am trying to insert into a table, but am getting an error message: "Error Executing Database Query.
Duplicate entry '13651' for key 'PRIMARY'"
I looked into the database and it appears a record with id 13651 already exists. So I think the problem is with mysql generating the right auto increment value.

It seems Auto_Increment value is damaged or not set to max value in that column. It's possible due to bulk insert.
So as per solution, set the maximum PK value + 1 as new AUTO_INCREMENT value. Now when you insert the records in this table, they will automatically pick the next incremented correctly.
ALTER.TABLE tablename AUTO_INCREMENT = value

Is the rest of the data for that record, and the one you are trying to insert, the same? If you you might just need to tell the ORM to replace that value?

If primary key has auto increment attribute turned on, do not insert it manually. remove that primary key part from your insert query (whatever the syntax according to the taste of your ORM framework).

Related

MySQL Auto_Increment trying to automatically insert prior used values

I Use Delphi 10.2, MySQL. I have a table that has about 50,000 records and has an Auto_Increment primary key. It has suddenly, and on it's own with no help from me, started trying to re-insert old key values. As a matter of fact, it started over with the value 1. I have no idea how to fix this and I hope you might be able to help.
Thanks,
Jim Sawyer
If the MySQL table is defined with an auto increment primary key then you should never specify the key value. MySQL should not re-use old key values, but you may want to check if there is any table corruption. You can also reset the table's auto-increment value using an ALTER TABLE command. (There's a tutorial on this here: https://www.mysqltutorial.org/mysql-reset-auto-increment)
You can use the Firedac monitoring to confirm whether or not you are sending the primary key to MySQL - set you connection to be monitored using the FireDAC component - they supply a monitoring tool that you can setup to see all of the SQL being transferred. Normally the Firedac layer would do an insert with no primary key and then use LAST_INSERT_ID to update the TField to have the actual value inserted.
If you are sending the wrong key then alter your logic so you don;t send the primary key on an insert.
you can reset the autoincrement value to any value you want with the following command
ALTER TABLE <table_name> AUTO_INCREMENT = <new value>;
so if new value is 100, the next inserted record receives a value of 100.

Duplicate entry for key 'PRIMARY' - even though it is set to AUTO_INCREMENT

Bit of a strange one - I haven't changed the config, database, PHP code for this site for about 8 years. The whole time the guy I made it for has been adding, removing, changing stock with no issue, and suddenly today gets this error:
Duplicate entry '2541' for key 'PRIMARY'
executing (inserted generic values for the texts):
INSERT INTO stock (id,title,category,description,price,last_update,sold) VALUES(NULL,'Item name','72','Item description','0',1613723525,'no')
Searching around seemed to suggest this was a common problem when the primary key is not set to auto increment - makes sense. However, checking it out through phpMyAdmin, it definitely is.
Is there something in the index being set to primary rather than unique?
There are 5 other tables on the database but none are linked (as in hard links through the SQL, PHP handles all the cross-table stuff).
I checked and indeed there IS an item in the stock table with ID 2541 already. So why is that NULL AUTO_INCREMENT value converting to an existing id?
EDIT
I noticed that a table I created more recently (via MySQL Workbench probably) has a different setup for the indexes, with the addition of an id_UNIQUE index - do I need one of these on the stock table that is causing issues?
Based on your description and your comment "Interestingly, each time I refresh the ID it is attempted to insert (and failing on) increments by 1", I suspect that somehow the seed for the autoincrement for that table got changed to some value that was inserted at some time before.
How exactly that could happen I don't know.
Now, each time you attempt to insert a record this internal counter increments, so you see in the error message that the number increases (2541, 2542, ...) When you attempt to insert a row the internal counter increments regardless of whether the transaction is committed to the database or not. In your case the insert operation is rolled back, because the generated value violates the unique constraint and the internal counter keeps growing.
To change the seed you can run the following statement:
ALTER TABLE stock AUTO_INCREMENT=1234567;
You'll need to set it to the current MAX value that exists in the table, so that new entries that the system attempts to insert do not conflict.
See also How to set initial value and auto increment in MySQL?
This answer shows how to change the autoincrement seed in MySQL Workbench and in PhpMyAdmin. Maybe somebody did this accidentally and didn't notice.

How to increment the Identity column

I am using identity columns as a primary key in my tables.
In some situations I need to work with primary keys before inserting a new row.
For example, in Oracle I use : select <sequence_name>.nextval into <variable> from dual
and I was sure that no one will insert any row with the same ID while my sp was executing.
As for SQL Server I can read the current identity value and it's increment, but there is no way to increment it without inserting a row.
Updated: The question is - how can I accomplish my task to work with ID (as identity column) in SQL Server before inserting a row and be sure that it will be unique at the end of my stored procedure.
Updated:I have a table with HierarchyId column.The way to form the first level of hierarchy,in my case, is to insert the hierarchyId column, according to indentity column. That is how I'v done it now:
begin transaction
insert into [dbo].[Group](GroupTypeId,CompanyOwnerId,GroupHierarchyId)
values(#GroupTypeId,#HeaderCompanyId,null)
update [dbo].[Group]
set GroupHierarcyId=hierarchyid::GetRoot().GetDescendant(cast ('/'+cast(#NewGroupId as varchar)+'/' as hierarchyid),null)
where GroupId=scope_identity()
commit
You can put an exclusive lock on the table, get the maximum ID, add 1 to it. That will be your next ID. Insert your data, the unlock the table.
HOWEVER,
I cannot fathom why you would want to work with a value before it is created. Can yo post a bit more information on that?
If you need a key that would be unique across databases and database servers, then the GUID's (Global Unique Identifier) certainly fulfills this need.
If you want to generate a new GUID server the you can simply use the NEWID() function
SELECT NEWID()

mysql delete and then insert. Does not insert into delete line for AI table! Why?

I am not sure I am correct in this.
I have insert 5 rows with values with id as primary key and autoincrement.
Then I delete row number 2-4.
when I insert on a new line with none id, the new id becomes "6". Is this normal?
How is it possible if you want the mysql to insert in the deleted row? what are the settings?
Yes, this is normal. If you want to insert with a specific ID number you have to specify that number on your insert statement.
The idea of auto increment is for the value to continually increase.
This is normal, though for some database engines you might receive 2, but usually it will be 6. In MSSQL it is possible to specify a value for an autoinc field with particular setting. Not sure what it is in mysql.
That's the expected behavior. Autoincrement primary keys are designed to be unique and continually increasing - so they are not assigned again.
If you TRUNCATE a table the autoincrement value is being reset while it stays as it is if you delete all rows with an DELETE query - that's a subtle but sometimes important difference.
As webdestroya suggested, the only possibility to reuse old and deleted autoincrement values is to set them specifically on the INSERT statement.

Inserting a record with specified primary key into MySQL via Entity Framework

We began using Entity Framework with MySQL in our project recently. Now I am writing unit tests for the data access level; for that purpose I have created a database with some test data.
In the test-method for the Delete method I want to first delete a specified record and then insert it again with all the fields holding exactly the same values, including the Id column which is set as the primary key. The purpose is to keep the test data in the DB.
But when I insert previously deleted record, Entity Framework just ignores the Id value of the entity and thus a new Id is generated using AUTO_INCREMENT.
Thanks in advance.
AUTO_INCREMENT means that you do not get to set the Id value, period. You just can't do this.
What you should do instead is:
Insert a new row.
SaveChanges()
Now read the Id value on the object, which will have been updated from the database.
Go ahead and delete the row, using this Id value.
Have you used the insert ignore statement?
It helps you forcefully insert pks with specified value.