As detailed in How can I get dict from sqlite query?, row_factory is helpful to get a dict when querying a SQLite database:
import sqlite3
conn = sqlite3.connect(":memory:")
conn.row_factory = sqlite3.Row
conn.execute('create table test (a text, b text, c int)')
conn.execute('insert into test values (?, ?, ?)', ('hello', 2, 17))
for r in conn.execute('select * from test'):
print(dict(r))
# {'a': 'hello', 'b': '2', 'c': 17}
The result of the query is directly a dict, which is sometimes very useful.
Question: is it also possible, when using row_factory to easily INSERT directly a dict into the database?
Here is a partial solution:
d = {'a': 1, 'b': 2, 'c': 3}
conn.execute('insert into test ({}) values ({})'.format(','.join(d.keys()), ','.join(['?'] * len(d))), tuple(d.values()))
but it's not really "pythonic".
Is there a cleaner way to insert a dict directly into a SQLite DB, for example, by using row_factory?
Side-remark: it would be great that it would also "auto-grow" the table definition, i.e. if I insert d = {'newkey': 1, 'b': 2, 'c': 3}, it would automatically add a new column to the table.