Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use executemany() to insert multiple rows but ignore the erroneous ones?

I am using Python MySQLdb to insert data into a mysql database.

InsertList contains many rows. All are valid except for a few which violate database integrity rules. If I run the code below, the command returns an error.

Cursor1.executemany(query, InsertList)

How can I force executemany() to insert the rows which are valid but ignore the few which are erroneous? The erroneous ones are caused by duplicate values in the new row. Do I have to use execute() one by one to insert the rows instead?

Thank you for your help.

like image 916
guagay_wk Avatar asked Dec 10 '25 14:12

guagay_wk


1 Answers

Use the SQL command

INSERT IGNORE INTO

instead of plain

INSERT INTO

Here is a reference to the docs. Note that there is also INSERT REPLACE (to replace duplicates with the new values) and INSERT ... ON DUPLICATE KEY UPDATE for more control.

like image 172
unutbu Avatar answered Dec 13 '25 02:12

unutbu