Python and SQLite: insert into table
conn = sqlite3.connect('/path/to/your/sqlite_file.db')
c = conn.cursor()
for item in my_list:
c.execute('insert into tablename values (?,?,?)', item)
there's a better way
# Larger example
rows = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
('2006-04-06', 'SELL', 'IBM', 500, 53.00)]
c.executemany('insert into stocks values (?,?,?,?,?)', rows)
connection.commit()
Not a direct answer, but here is a function to insert a row with column-value pairs into sqlite table:
def sqlite_insert(conn, table, row):
cols = ', '.join('"{}"'.format(col) for col in row.keys())
vals = ', '.join(':{}'.format(col) for col in row.keys())
sql = 'INSERT INTO "{0}" ({1}) VALUES ({2})'.format(table, cols, vals)
conn.cursor().execute(sql, row)
conn.commit()
Example of use:
sqlite_insert(conn, 'stocks', {
'created_at': '2016-04-17',
'type': 'BUY',
'amount': 500,
'price': 45.00})
Note, that table name and column names should be validated beforehand.