亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從變量插入 sqlite3

從變量插入 sqlite3

www說 2023-10-25 10:59:21
我一直在嘗試創建一個數據庫,我的表的列名來自一個列表:import sqlite3L     = ["Nom","Age","Taille"]list2 = ["Karl", "11", "185"]M = []R = 0con = sqlite3.connect(":memory:")con.execute("CREATE TABLE master ("+",".join(L)+")")然后要么:for e in L:    R += 1    con.execute("INSERT INTO master("+",".join(L)+") VALUES (?,?,?)",list2[R-1])或者for e in L:    R += 1    con.execute("INSERT INTO master(e) VALUES (?)",list2[R-1])或者listX=[list2[0],list2[1],list2[3])con.executemany("INSERT INTO master ("+",".join(L)+") VALUES ("+",".join(M)+")", (listX))
查看完整描述

1 回答

?
拉丁的傳說

TA貢獻1789條經驗 獲得超8個贊

在你的情況下:

import sqlite3


con = sqlite3.connect(":memory:")

columns = ["Nom", "Age", "Taille"]

columns_str = '"' + '","'.join(columns) + '"'

con.execute(f"CREATE TABLE people ({columns_str})")


data = [

? ('Karl', 11, 185)

]

stmt = f"INSERT INTO people ({columns_str}) VALUES (?, ?, ?)"

con.executemany(stmt, data)

另外,可能不要打電話給你的桌子master——稍后會變得非?;靵y。L像和 之類的名字list2也沒有幫助。明確命名變量,按照它們的含義或包含的內容命名。未來的你會感謝你的。


也許更干凈一點:


import sqlite3


con = sqlite3.connect(":memory:")

columns = ("Nom", "Age", "Taille")

con.execute("CREATE TABLE people (%s, %s, %s)" % columns)


data = [

? ('Karl', 11, 185)

]

stmt = f"INSERT INTO people (%s, %s, %s) VALUES (?, ?, ?)" % columns

con.executemany(stmt, data)


查看完整回答
反對 回復 2023-10-25
  • 1 回答
  • 0 關注
  • 148 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號