I am inserting a list of dictionaries to a PostgreSQL database. The list will be growing quickly and the number of dict values (columns) is around 30. The simplified data:
projects = [
{'name': 'project alpha', 'code': 12, 'active': True},
{'name': 'project beta', 'code': 25, 'active': True},
{'name': 'project charlie', 'code': 46, 'active': False}
]
Inserting the data into the PostgreSQL database with the following code does work (as in this answer), but I am worried about executing too many queries.
for project in projects:
columns = project.keys()
values = project.values()
query = """INSERT INTO projects (%s) VALUES %s;"""
# print(cursor.mogrify(query, (AsIs(','.join(project.keys())), tuple(project.values()))))
cursor.execute(query, (AsIs(','.join(columns)), tuple(values)))
conn.commit()
Is there a better practice? Thank you so much in advance for your help!