Insert with execute many, skipping rows that fail foreign key constraints

329 Views Asked by At

I am using Python mysql.connector . I have to make a lot of inserts. The data I am inserting is likely to have some rows that will fail the foreign key constraint and thus return the 1452 mysql error.

 add_specific="""
INSERT INTO `specific info type`
(`name`, `Classification Type_idClassificationType`)
VALUES
(%s, %s);
"""
cursor.executemany(add_specific, specific_info)

Is there a way where I can execute all of the inserts and in the event of a 1452 that example would just be skipped. I read the executemany is more efficient so I would prefer to use it. I guess I could iterate through all examples and make individual inserts and catch the exception.

1

There are 1 best solutions below

0
On BEST ANSWER

Use INSERT IGNORE INTO whatever and MySQL will ignore the rows that fail insertion.