好的,基本上我正在尝试使用实例变量(typ 和 lvl)更新现有的 SQLite3 数据库
#Set variables
typ = 'Test'
lvl = 6
#Print Databse
print("\nHere's a listing of all the records in the table:\n")
for row in cursor.execute("SELECT rowid, * FROM fieldmap ORDER BY rowid"):
print(row)
#Update Info
sql = """
UPDATE fieldmap
SET buildtype = typ, buildlevel = lvl
WHERE rowid = 11
"""
cursor.execute(sql)
#Print Databse
print("\nHere's a listing of all the records in the table:\n")
for row in cursor.execute("SELECT rowid, * FROM fieldmap ORDER BY rowid"):
print(row)
作为一个错误,我得到了
sqlite3.OperationalError: no such column: typ
现在我基本上知道问题是我的变量是用错误的语法插入的,但我一辈子都找不到正确的变量。它可以像这样处理字符串和整数:
sql = """
UPDATE fieldmap
SET buildtype = 'house', buildlevel = 3
WHERE rowid = 11
"""
但是一旦我切换到变量,它就会抛出错误。
请您参考如下方法:
您的查询实际上并未将变量 typ 和 lvl 的值插入到查询字符串中。如所写,查询试图引用名为 typ 和 lvl 的列,但表中不存在这些列。
尝试将 is 作为参数化查询编写:
sql = """
UPDATE fieldmap
SET buildtype = ?, buildlevel = ?
WHERE rowid = 11
"""
cursor.execute(sql, (typ, lvl))
? 充当查询字符串中的占位符,由传递给 execute() 的元组中的值替换。这是构建查询并避免 SQL 注入(inject)漏洞的安全方法。
