好的,基本上我试图用实例变量(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
但是一旦切换到变量,它就会抛出错误。
答案 0 :(得分:2)
您的查询实际上并未将变量typ
和lvl
的值插入查询字符串中。正如所写,查询试图引用名为typ
和lvl
的列,但这些列不存在于表中。
尝试写作是参数化查询:
sql = """
UPDATE fieldmap
SET buildtype = ?, buildlevel = ?
WHERE rowid = 11
"""
cursor.execute(sql, (typ, lvl))
?
充当查询字符串中的占位符,该字符串由传递给execute()
的元组中的值替换。这是构建查询的安全方法,可以避免SQL注入漏洞。
答案 1 :(得分:-1)
嘿,我认为你应该使用ORM来操作SQL数据库。
SQLAlchemy是你的朋友。我在SQLite,MySQL,PostgreSQL中使用它。太棒了。
这可以使您远离此语法错误,因为SQL确实将逗号和引号视为重要性。
对于硬编码,您可以尝试这样做:
sql = """
UPDATE fieldmap
SET buildtype = '%s', buildlevel = 3
WHERE rowid = 11
""" % (house)
这可以暂时解决您的问题,但从长远来看并非如此。 ORM是你的朋友。
希望这可能有所帮助!