Skip to content

Instantly share code, notes, and snippets.

@draplater
Last active October 3, 2015 15:57
Show Gist options
  • Save draplater/c184c01ec926bcccb1f0 to your computer and use it in GitHub Desktop.
Save draplater/c184c01ec926bcccb1f0 to your computer and use it in GitHub Desktop.
Insert a python dict like object to a sqlite3 table
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