There is a list of dictionaries of the form:

[{"1":"1","2":"1"},...] 

in which the keys of the dictionaries are columns in the database table. That is, all dictionaries with the same keys, but with different values. I need to add these values ​​to the table.

How to implement it?

  • Give a small example of data and DDL ( create table ... ) tables. Are all table fields present in dictionaries? Is it planned to update, rewrite or create a table? - MaxU
  • All table fields are present in dictionaries, that is, the table has columns 1, 2, 3 ... each dictionary has keys 1, 2, 3 ... but in the same sequence. The table will not be updated. - Hutado Hutado 6:59 pm

2 answers 2

You can use the Pandas module:

 import pandas as pd from sqlalchemy import create_engine data = [{'a':1, 'b':'string1'}, {'a':2, 'b':'string2'}, {'a':3, 'b':'string3'}] # create SQL Alchemy DB connection # conn = create_engine('postgresql://user:password@host:port/dbname') conn = create_engine('postgresql+psycopg2://user:password@host:port/dbname') # create Pandas DataFrame from the list of records df = pd.DataFrame(data) # write DF into SQL table df.to_sql('table_name', conn, if_exists='replace', index=False) 

DataFrame example:

 In [74]: df Out[74]: ab 0 1 string1 1 2 string2 2 3 string3 
  • 2
    Yes, it really is a solution to my problem, thanks! - Hutado Hutado

Found another solution using psycopg2. It took due to the fact that pandas does not support python 3.4.

 import psycopg2 out = [{'a':1,'b':2,'c':3}, {'a':4,'b':5,'c':6}] with psycopg2.connect("dbname='dbname' user='user' host='host' password='password'") as conn1: with conn1.cursor() as cur: cur.execute("CREATE TABLE table (a varchar, b varchar, c varchar);") cur.executemany("INSERT INTO table VALUES (%(a)s, %(b)s, %(c)s);", out) conn1.commit() 
  • Interesting parameterized filling of the request :) And if we had a list / tuple, was it possible to executemany ? use? - gil9red
  • one
    Pandas to version 0.20.x officially supports Python 3.4 - MaxU
  • one
    @ gil9red, yes, question marks can also be used. A total of 5 different styles can be used for the "prepared statements" - MaxU