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

后端 未结 5 1051
别那么骄傲
别那么骄傲 2020-12-09 05:43

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

5条回答
  •  南笙
    南笙 (楼主)
    2020-12-09 06:03

    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)
    

提交回复
热议问题