好吧,基本上我正在尝试使用实例变量(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
的列,但这些列在表中不存在。
尝试将其写为参数化查询:
sql = """
UPDATE fieldmap
SET buildtype = ?, buildlevel = ?
WHERE rowid = 11
"""
cursor.execute(sql, (typ, lvl))
?
充当查询字符串中的占位符,该占位符被传递给 execute()
的元组中的值替换。这是一种构建查询的安全方法,可以避免 SQL 注入(inject)漏洞。
关于python - 在 SQLite3 更新中使用实例变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36853235/