Python and SQLite: insert into table

后端 未结 6 558
梦如初夏
梦如初夏 2020-12-08 00:08

I have a list that has 3 rows each representing a table row:

>>> print list
[laks,444,M]
[kam,445,M]
[kam,445,M]

How to insert thi

6条回答
  •  时光说笑
    2020-12-08 01:06

    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.

提交回复
热议问题