a="1"
b="2"
c="3"
d="4"
user1 = {"id": 100, "name": "Rumpelstiltskin", "dob": "12/12/12", "item": [{"name": "sakthi"}]}
con = sqlite3.connect(database=r'data.db')
cur = con.cursor()
cur.execute("INSERT INTO e_transations (eid,sl,id,datee,ent) VALUES (?,?,?,?,?)",(a,b,c,d,user1,))
con.commit()
如何使用python在sqlite3中插入字典
user1 被保存到單列單行
EX :( 1 2 3 4 {"id": 100, "name": "Rumpelstiltskin", "dob": "12/12/12", "item": [{"name": "sakthi"}]} )
將上述格式保存在 sqlite3 中
uj5u.com熱心網友回復:
你不能那樣做。您可以做的最接近的是使用 json.dumps 將字典序列化為字串,然后將結果字串存盤到 sqlite3 中的列中。
import json
serialised = json.dumps(<dictionary here>)
...
cur.execute("INSERT INTO e_transations (eid, sl, id, datee, ent) VALUES (?, ?, ?, ?, ?)", (a, b, c, d, serialised))
uj5u.com熱心網友回復:
您可以使用“命名”引數替換樣式從字典中獲取 SQL 陳述句值。而不是使用?,使用:keywhere key 是字典中的鍵。
data = {'foo': 1, 'bar': 2, 'baz': 3}
with sqlite3.connect(':memory:') as conn:
conn.execute("""CREATE TABLE t (foo integer, bar integer, baz integer)""")
conn.execute("""INSERT INTO t (foo, bar, baz) VALUES (:foo, :bar, :baz)""", data)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/311422.html
