Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python : How to insert a dictionary to a sqlite database?

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 ?

like image 357
avee137 Avatar asked Jun 06 '12 11:06

avee137


People also ask

How do you embed a dictionary in Python?

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.

How do I populate a SQLite database in Python?

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.

How do you append a dictionary?

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.


2 Answers

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)
like image 81
Gareth Webber Avatar answered Sep 20 '22 11:09

Gareth Webber


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)
like image 38
himself Avatar answered Sep 17 '22 11:09

himself