在 SQLite3 更新中使用实例变量?
Using instance variables in SQLite3 update?
好的,基本上我正在尝试使用实例变量(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
"""
但是一旦我切换到变量,它就会抛出错误。
嘿,我认为你应该使用 ORM 来操作 SQL 数据库。
SQL炼金术是你的朋友。我将它与 SQLite、MySQL、PostgreSQL 一起使用。太棒了。
这可以让你摆脱这个语法错误,因为 SQL 确实很重视逗号和引号。
对于硬编码,你可以试试这个:
sql = """
UPDATE fieldmap
SET buildtype = '%s', buildlevel = 3
WHERE rowid = 11
""" % (house)
这可以暂时解决您的问题,但不能长久运行。 ORM 是你的朋友。
希望这对您有所帮助!
您的查询实际上并未将变量 typ
和 lvl
的值插入到查询字符串中。如所写,查询试图引用名为 typ
和 lvl
的列,但这些在 table.
中不存在
尝试将其写为参数化查询:
sql = """
UPDATE fieldmap
SET buildtype = ?, buildlevel = ?
WHERE rowid = 11
"""
cursor.execute(sql, (typ, lvl))
?
充当查询字符串中的占位符,它被传递给 execute()
的元组中的值替换。这是构建查询并避免 SQL 注入漏洞的安全方法。
好的,基本上我正在尝试使用实例变量(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
"""
但是一旦我切换到变量,它就会抛出错误。
嘿,我认为你应该使用 ORM 来操作 SQL 数据库。
SQL炼金术是你的朋友。我将它与 SQLite、MySQL、PostgreSQL 一起使用。太棒了。
这可以让你摆脱这个语法错误,因为 SQL 确实很重视逗号和引号。
对于硬编码,你可以试试这个:
sql = """
UPDATE fieldmap
SET buildtype = '%s', buildlevel = 3
WHERE rowid = 11
""" % (house)
这可以暂时解决您的问题,但不能长久运行。 ORM 是你的朋友。
希望这对您有所帮助!
您的查询实际上并未将变量 typ
和 lvl
的值插入到查询字符串中。如所写,查询试图引用名为 typ
和 lvl
的列,但这些在 table.
尝试将其写为参数化查询:
sql = """
UPDATE fieldmap
SET buildtype = ?, buildlevel = ?
WHERE rowid = 11
"""
cursor.execute(sql, (typ, lvl))
?
充当查询字符串中的占位符,它被传递给 execute()
的元组中的值替换。这是构建查询并避免 SQL 注入漏洞的安全方法。