Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy INSERT IGNORE

How can I insert multiple data records into table ignoring duplicates. I am using SQLAlchemy.

Thank you!

like image 820
spacemonkey Avatar asked Feb 07 '10 20:02

spacemonkey


People also ask

What is insert ignore into?

The INSERT IGNORE command keeps the first set of the duplicated records and discards the remaining. The REPLACE command keeps the last set of duplicates and erases out any earlier ones. Another way to enforce uniqueness is to add a UNIQUE index rather than a PRIMARY KEY to a table.

How do I update data in SQLAlchemy?

Update table elements in SQLAlchemy. Get the books to table from the Metadata object initialized while connecting to the database. Pass the update query to the execute() function and get all the results using fetchall() function. Use a for loop to iterate through the results.

How do I delete a table in SQLAlchemy Python?

Just call drop() against the table object. From the docs: Issue a DROP statement for this Table, using the given Connectable for connectivity.


1 Answers

prefix_with("TEXT") adds arbitrary text between INSERT and the rest of the SQL. execute() accepts a list of dictionaries with the records you would like to insert or a single dictionary if you only want to insert a single record.

The SQLite syntax for the behavior you're looking for:

inserter = table_object.insert().prefix_with("OR REPLACE") inserter.execute([{'column1':'value1'}, {'column1':'value2'}]) 
like image 102
joeforker Avatar answered Sep 28 '22 05:09

joeforker