Last active
October 3, 2015 15:57
-
-
Save draplater/c184c01ec926bcccb1f0 to your computer and use it in GitHub Desktop.
Insert a python dict like object to a sqlite3 table
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def smart_insert(db, table, dic, cols=None): | |
""" | |
eg: smart_insert(db, 'employee', {'name': 'Peter', 'age': 18}) | |
""" | |
cur = db.cursor() | |
if not cols: | |
cols = dic.keys() | |
columns = ', '.join(cols) | |
placeholders = ', '.join('?' * len(cols)) | |
sql = 'INSERT INTO {} ({}) VALUES ({})'.format(table, columns, | |
placeholders) | |
cur.execute(sql, [dic[i] for i in cols]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment