python - 在 SQLite3 更新中使用实例变量?

标签 python sqlite instance-variables

好吧,基本上我正在尝试使用实例变量(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
"""

但是一旦我切换到变量,它就会抛出错误。

最佳答案

您的查询实际上并未将变量 typlvl 的值插入到查询字符串中。正如所写,查询尝试引用名为 typlvl 的列,但这些列在表中不存在。

尝试将其写为参数化查询:

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/

相关文章:

ruby - 这两个 Ruby 类初始化定义有什么区别?

java 。我的一个类的用户输入没有返回到主程序

python - 使用opengl4,可以将`uniform`变量映射到我的用户空间内存吗?

由于缩进而导致 Python 打印错误

c# - 如何使用 EF5 包含从一种数据库类型到另一种实体类型的转换?

sql - 大型SELECT查询似乎向相同但较小的SELECT查询返回不同的顺序?

python - 具有非重复字符的最长子串

python - 为重复记录创建新的平均分数 [userid, itemid]

android - 搜索标记的搜索框(谷歌地图)

ruby - 在 :each clause of a MiniTest 之前递增一个实例变量