TAGS :Viewed: 8 - Published at: a few seconds ago

[ Insert a list of dictionary using sqlalchemy efficiently ]

I have a list containing dictionaries as elements. All the dictionaries confronts to my schema, is there a simple or efficient way to insert these details in db with sqlalchemy?

my list is below

[{id:'12',name:'a':lang:'eng},{id:'13',name:'b':lang:'eng},{id:'14',name:'c':lang:'eng}]

and I am having a schema given below

id String(10)
name String(10)
lang String(10)

Answer 1


As stated in SQLAchemy documentation, you can insert many records in your table by calling your connection.execute() method, using table.insert() and your list of records as it's parameters, like this:

connection.execute(table.insert(), [ 
        {id:'12',name:'a':lang:'eng'},
        {id:'13',name:'b':lang:'eng'},
        {id:'14',name:'c':lang:'eng'},
    ]
)

Assuming, of course, that your table really has those column names as stated in your dictionary's keys and your values doesn't violate any constraint that you might have defined.