phpMyAdmin export/import results in duplicate primary key error - mysql

I want to globally replace all instances of my site url in the Wordpress MySQL database with a new site url. To do that, I'm using phpMyAdmin to export the database to a .sql file, then doing a global replace in a text editor, then using phpMyAdmin to import the .sql file.
During the import, I'm encountering a duplicate entry for primary key error. Trying to debug this, I exported the file, then imported the identical file, making no changes and I still get the same error.
I appreciate any help solving this.
--
-- Dumping data for table `wp_comments`
--
INSERT INTO `wp_comments`
(`comment_ID`, `comment_post_ID`, `comment_author`, `comment_author_email`
,`comment_author_url`, `comment_author_IP`, `comment_date`, `comment_date_gmt`
,`comment_content`, `comment_karma`, `comment_approved`, `comment_agent`
,`comment_type`, `comment_parent`, `user_id`)
VALUES (1, 1, 'Mr WordPress', ''
,'http://wordpress.org/', '', '2011-04-28 00:49:55', '2011-04-28 00:49:55'
,'Hi, this is a comment.<br />To delete a comment,
just log in and view the post's comments.
There you will have the option to edit or delete them.'
, 0, 'post-trashed', '', '', 0, 0 ) ;
MySQL said:
#1062 - Duplicate entry '1' for key 'PRIMARY'

The original data is still in the database.
If you were working manually you'd send a UPDATE rather than INSERT query with the new values, but since you're doing a batch import, it may just be better to wipe the existing table clean before the import.
DELETE FROM `tblName`;
Be sure to back-up your data, first.

To avoid duplicates you have to use UPDATE instead of INSERT statements. To achieve this in phpMyAdmin, follow these steps:
Select your database in the tree.
OPTIONAL. Go to "Search" tab and search for string you want to replace in all tables. If string is found in several tables only, note their names. This will help to speed up process by updating only the tables which needs updating. This my be important if you have lot of data.
Go to "Export" tab.
In the "Export method:" select "Custom".
OPTIONAL. If you noted the tables which need updating in step 2 above, then in the "Table(s):" section, click "Unselect all" and then select only the tables which need to be updated.
Scroll down to "Data creation options" section, and in the drop
box labeled "Function to use when dumping data:" select "UPDATE"
(default is "INSERT").
Click "Go".
Open the downloaded SQL dump file.
IMPORTANT! Save the file with a new name for backup purposes before any changes are made.
Use Search & replace function of your editor to change what you want. Then save the file.
In phpMyAdmin go to "Import" tab.
In the "File to import:" section click the "Choose file" button and
browse for the edited file. Click GO
You are ready! To check if everything is OK, search the database second time (repeat step 2). You should not find any tables containing your old string.

If you're exporting, that means that the main content stays in the database. So, when you try to insert a new row with the same PRIMARY KEY, which are always UNIQUE, you'll get an error.
Solution: You must delete the row from the table that has the same comment_ID.
You must open the PHPMyAdmin and go your table page, and check the row with the ID you want. In this case is 1, which means that it is probabily in the first results page of your table listing. Just click on the red X which appears in the row.
This could also be done by SQL, which could be simple too.
DELETE FROM `wp_comments` WHERE `comment_ID` = 1 LIMIT 1
For this, just select your database in PHPMyAdmin and go to the SQL tab, and insert the code above in the text area.

Had the same problem and error number. Deleted the database, recreate with no tables, and import the changed export file worked for me.

The problem is related with your file - you are trying to create a DB using a copy - at the top of your file you will find something like this:
CREATE DATABASE IF NOT EXISTS *THE_NAME_OF_YOUR_DB* DEFAULT CHARACTER SET latin1 COLLATE latin1_general_ci;
USE *THE_NAME_OF_YOUR_DB*;
and I'm sure that you already have a DB with this name - IN THE SAME SERVER - please check, because you are trying to overwrite!! Just change the name OR (better) ERASE THIS LINE!

Since you already have that record there, you can just update the record rather than inserting. It would go something like this.
UPDATE `wp_comments`
SET 'comment_author_url' = 'YOUR NEW ADDRESS'
WHERE `comment_ID` = 1
Just update every instance of your old address using this method. You can search through all of all posts by saying "WHERE 'comment_author_url' = 'YOUR OLD ADDRESS'"

If all you want to do is replace your URL, I believe this is all you must do:
Update `wp_comments` Set
`comment_author_url` = 'http://wordpress.org/'
Where `comment_author` = 'Mr WordPress'
Just type the above SQL into PHPMyAdmin's SQL box and execute.
NOTE: First make sure you have a backup. And there's no need to do all that export and import stuff :)

Change to code to
INSERT .... (what you already have)
ON DUPLICATE KEY UPDATE;
This will fix your problem with a minimum of fuss, whilst still inserting new rows.

Related

How to resolve Write Conflict error in MS Access when writing unchanged record to MySQL via ODBC?

If the user manually reverts a change to a field in a linked table in Access resulting in the record being unmodified overall, the 'Write Conflict' error message will be displayed when attempting to save the record. An example would be that the user makes a single change to a record by changing a field from 10 to 20, and then without saving the record re-enters the original value of 10.
Office Pro Plus 2016
MySQL 8.028
To reproduce this behaviour:
Create a test database in MySQL
CREATE SCHEMA test;
USE test;
CREATE TABLE testtable (
ID INT NOT NULL,
ts TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
col1 INT NULL DEFAULT NULL,
col2 INT NULL DEFAULT NULL,
PRIMARY KEY (ID))
ENGINE = InnoDB;
Create an ODBC connection to the test database using a a user DSN and ANSI MySQL driver
Create a blank access database and link to the testtable
Open testtable and enter and save a couple of dummy rows. Change the value in one of the col fields. Without navigating away from the row or using undo, type the original value back into the field. Attempt to save the row.
I have deliberately included timestamp to demonstrate that this is not a fix.
I would appreciate advice from anyone who knows what causes this behaviour and how to prevent it.
I found a workaround for this which is not ideal but it does work. I've added a boolean field to the SQL table called changeflag. In the OnDirty event of the Access form I call a simple procedure to change the value of this field. This way even if the user manually undoes a change that they made, there is still a change to the data somewhere else and the write conflict no longer occurs. The code is below.
Private Sub Form_Dirty(Cancel As Integer)
changeflag = Not changeflag
End Sub
Turns out the solution is buried in the MYSQL ODBC documentation, the FOUND_ROWS connector/ODBC option needs to be set. In the GUI, it's under Cursor/Results tab of the Data source configuration: 'Return matched rows instead of affected rows'. After changing this setting, the conflicts no longer occur.

INSERT even though column does not exist in MySQL

Let's say I have an old .SQL dump and since it was created, I have changed the table schema.
I could be running:
INSERT INTO `ec_product_campaign_relations` (`campaign_id`, `product_id`, `product_qty`) VALUES (30,28,1),(30,27,0),(30,31,0),(30,30,0);
But if column product_qty does no longer exist, the line will not get inserted.
How can I force the line to get inserted anyways and ignore that the column does not exist?
EDIT: It should mention I'm working in PHP and it is script used to sync table shema... So no "manual" control over this.
Since editing all your SQL dump won't be trivial, I suggest you to add the column to your table, make the import, then delete the column.
You might want to create a new database for this import and restore the dump as-is. Then, once you've got a handle on what changes have been made by comparing the schema in one to the new one, create a series of ALTER TABLE statements that bring it in sync.
I tend to record these in a text file in case I need to replay them later, and also keep them as a list of what's changed. You may have to do this more than once, so notes help.
Then, once you've cleaned them up to be column-compatible, dump this database table-by-table, and restore into the other as required.

#1062 - Duplicate entry '1' for key 'PRIMARY'

I am at a complete loss here. I have two databases. One on my localhost site that I use for development and one on my remote site that I use for my live (production) site. I manage both of them through phpMyadmin. As I have been doing for months now, when I need to update the live site, I dump the related database and import the database from my localhost site.
Now, no matter what I try, I keep getting this error:
Error
SQL query:
--
-- Dumping data for table `oc_address_type`
--
INSERT INTO `oc_address_type` ( `address_type_id` , `address_type_name` )
VALUES ( 1, 'Billing' ) , ( 2, 'Shipping' ) ;
MySQL said: Documentation
#1062 - Duplicate entry '1' for key 'PRIMARY'
I tried creating a new blank database on my localhost and importing into that but same results. I have validated all of the tables and indexes and cannot find anything wrong there.
Any suggestions please as I am completely down until this gets resolved.
By the way, I am completely dropping all tables and importing structure and data. This has always worked until today.
you need to dump with the drop statements. The table exists and has data already and your trying to insert more which is identical. Im not 100% sure on phpmyadmin but the dumps will have an option for "add drop table" statements
Dump your database on localhost with "mysqldump --insert-ignore ..." then try to import with phpmyadmin on your live machine.
Or try to connect to your live database with command line tools (configure your database to be able to connect from other hosts than "localhost" first!)
Then you can try following:
$ mysql -f -p < yourdump.sql
with -f "force" you can ignore errors during importing. It's the same as adding "--force" parameter to "mysqlimport".
The problem is related with your file - you are trying to create a DB using a copy - at the top of your file you will find something like this:
CREATE DATABASE IF NOT EXISTS *THE_NAME_OF_YOUR_DB* DEFAULT CHARACTER SET latin1 COLLATE latin1_general_ci; USE *THE_NAME_OF_YOUR_DB*;
and I'm sure that you already have a DB with this name - IN THE SAME SERVER - please check, because you are trying to overwrite!! Just change the name OR (better) ERASE THIS LINE!
For me the foreign_key_checks and truncate table options was useful.
SET foreign_key_checks = 0;
TRUNCATE `oc_address_type`;
SET foreign_key_checks = 1;
Run the above sql script, and after the import.
I had this same issue, my problem was I had a primary key column called unique_id and when you try to add two of the same value in that primary keyed column, it comes back with the error below.
A primary key column's data is all suppose to be different, so that bottom 1 I changed to 3 and the error went away.
Your MySql is not corrupt, like previous answers and comments.
you need to delete any previous tables that you are over-writing. if you are doing a complete restore of all tables, delete all existing tables.
I have met the same problem, I drop the table and rebuilt the database, then the problem solved.

Merge tables without overwriting existing ones in mysql phpmyadmin

I was having a "coming soon" page with a sign up form. Since a couple of weeks I've switched to another web hosting and continue working on my new site at my new host, but continued to let the visitors sign up at my old host.
Now my have pointed my domain to my new hosting and want to export all new subscribers and import them into the new DB. Some rows might use same ID.
How can I easily export and merge a table from the old DB to the new one? Please note I don't wan't it to overwrite any row that has the same ID, if it does, I want it to add a new row instead.
I've tried exporting my table "wp_csp3_subscribers" from my old DB and imported it in my new one. But get an error saying ID already exists.
If you're using phpMyAdming (based on your tags), you can expand the export options by selecting "Custom - display all possible options" instead of the default "Quick - display only the minimal options".
Under the data dump options, choose "INSERT IGNORE statements", which will tell mySQL to ignore any errors with duplicate primary keys.
Taken from the mySQL documentation on the IGNORE option:
For example, without IGNORE, a row that duplicates an existing UNIQUE index or PRIMARY KEY value in the table causes a duplicate-key error and the statement is aborted. With IGNORE, the row still is not inserted, but no error is issued.
Hope this answers your question.
also, if you have two sql files from a dump, insert one normally, maybe with Enable foreign key checks unchecked, then your second file would like to concatenate the data, remove the DROP TABLE IF EXISTS and CREATE TABLE lines in that second file. Leave only the LOCK TABLES table WRITE; and inserts

phpMyAdmin: MySQL Error 1062 - Duplicate entry

I connect with user "root" onto my database "test" which I host locally for development. Among others I have the table "ratingcomment". For some reason when I click on the table "ratingcomment" phpMyAdmin shows me the following error:
Fehler
SQL-Befehl:
INSERT INTO `phpmyadmin`.`pma_history` (
`username` ,
`db` ,
`table` ,
`timevalue` ,
`sqlquery`
)
VALUES (
'root', 'test', 'ratingcomment', NOW( ) , 'SELECT * FROM `ratingcomment`'
)
MySQL meldet:
#1062 - Duplicate entry '838' for key 'PRIMARY'
I used google to finde out the following
"This indicates that you have a UNIQUE or PRIMARY index on a table, and there is a duplicate value someone on one of the values in one of these indexes."
But I still dont quite understand the error! I use a primary Key, which auto-increments for all of my tables, so there actually shouldnt be a problem with the table. I had another table named "rating" which had a column "comment". Can it be, that this causes problems?
Quick fix:
REPAIR TABLE `phpmyadmin`.`pma_history`
If that fails, I'd just truncate/empty the table.
TRUNCATE TABLE `phpmyadmin`.`pma_history`
Although phpmyadmin has it's place in my toolbox, I personally don't use it's internal db.
ADDENDUM
MyISAM tables can easily become corrupted. A couple causes that usually hit me: if the MySQL is not shutdown properly, or if the table has a FULLTEXT index and the stopword file on disk had changed.
Simply stated, the REPAIR just checkes the data file for errors (and depending on your options, makes it usable again) and rewrites the index file. Fair warning: with MyISAM, repairing a table can often toast all your data in that table to make it usable. See doc for more details.
A google search pertaining to this pma table being corrupted lead me to this.
This appears to be an internal error. You've issued this query:
SELECT * FROM `ratingcomment`
phpMyAdmin tries to write such action in its internal event log and it fails. If you Google for pma_history you'll find several references to such table being corrupted.
My advice is that you find another SQL client (such as HeidiSQL) and try to repair the phpMyAdmin database.
I know this is kinda late but I had the same problem and wanted to share what I did.
In PhpMyAdmin, I went to the table's Operation tab, and just incremented the AUTO_INCREMENT value under Table options and inserted a dummy record.