I have a sqlite database with a table with following columns :
id(int) , name(text) , dob(text)
I want to insert following dictionary to it :
{"id":"100","name":"xyz","dob":"12/12/12"}
Dictionary keys are the column names. How can i achieve it ?
Python add to Dictionary using “=” assignment operator We do not have any specific Python way to update a dictionary. If you want to add a new key to the dictionary, then you can use the assignment operator with the dictionary key. This is pretty much the same as assigning a new value to the dictionary.
First, connect to the SQLite database by creating a Connection object. Second, create a Cursor object by calling the cursor method of the Connection object. Third, execute an INSERT statement. If you want to pass arguments to the INSERT statement, you use the question mark (?) as the placeholder for each argument.
Appending element(s) to a dictionary To append an element to an existing dictionary, you have to use the dictionary name followed by square brackets with the key name and assign a value to it.
Looking at the documentation here you can add a single row:
c.execute("INSERT INTO stocks VALUES (?,?,?)", [dict["id"], dict["name"], dict["dob"]])
Or you can use a list and add multiple rows in one go:
# Larger example that inserts many records at a time
purchases = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
('2006-04-05', 'BUY', 'MSFT', 1000, 72.00),
('2006-04-06', 'SELL', 'IBM', 500, 53.00),
]
c.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases)
Here's a way which preserves parameter safety. (Might need polishing in the tablename department)
def post_row(conn, tablename, rec):
keys = ','.join(rec.keys())
question_marks = ','.join(list('?'*len(rec)))
values = tuple(rec.values())
conn.execute('INSERT INTO '+tablename+' ('+keys+') VALUES ('+question_marks+')', values)
row = {"id":"100","name":"xyz","dob":"12/12/12"}
post_row(my_db, 'my_table', row)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With