[英]Python SQLite3 Insert
我插入值時出錯。 我的數據庫有3列。 一個自動增量整數在這里初始化:
connection.execute("CREATE TABLE IF NOT EXISTS {tn} ({nf1} {ft1} PRIMARY KEY AUTOINCREMENT)"\
.format(tn = tableName, nf1 = "IDPK", ft1 = "INTEGER"))
和兩個文本字段初始化如下:
connection.execute("ALTER TABLE {tn} ADD COLUMN '{cn}' {ct}".format(tn = tableName, cn = "foo", ct = "TEXT"))
connection.execute("ALTER TABLE {tn} ADD COLUMN '{cn}' {ct}".format(tn = tableName, cn = "bar", ct = "TEXT"))
執行在這里:
connection.execute("INSERT INTO {tn} VALUES (NULL, {col1}, {col2})".format(tn = tableName, col1 = text1, col2 = text2))
拋出的錯誤是:
sqlite3.OperationalError: no such column: "obfuscatedTextStringInText1"
我不明白為什么它認為列的名稱在text1中。 我正在使用這種語法在第1列和第2列中插入一個值,因為autoincrement函數帶有NULL關鍵字。
不要使用字符串格式將變量插入查詢。 這很危險(你很容易受到SQL注入攻擊 )和錯誤提示(正如你已經看到的那樣)。
相反, 參數化您的查詢:
connection.execute("""
INSERT INTO
{tn}
VALUES
(NULL, :col1, :col2)""".format(tn=tableName),
{"col1": text1, "col2": text2})
請注意,我們無法參數化表或列名稱 - 請確保驗證並正確轉義tableName
,或信任您的源。
應該引用arround {col1}
和{col2}
因為它們是作為文本值插入的。 例如,它目前正在評估如下:
"INSERT INTO table_name VALUES (NULL, my text 1, my text 2)"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.