【问题标题】:Using instance variables in SQLite3 update?在 SQLite3 更新中使用实例变量?
【发布时间】:2016-08-19 14:11:46
【问题描述】:

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

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

【问题讨论】:

    标签: python sqlite instance-variables


    【解决方案1】:

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

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

    sql = """
    UPDATE fieldmap
    SET buildtype = ?, buildlevel = ?
    WHERE rowid = 11
    """
    
    cursor.execute(sql, (typ, lvl))
    

    ? 充当查询字符串中的占位符,它被传递给execute() 的元组中的值替换。这是构造查询的一种安全方式,可以避免 SQL 注入漏洞。

    【讨论】:

      【解决方案2】:

      嘿,我认为你应该使用 ORM 来操作 SQL 数据库。

      SQLAlchemy 是你的朋友。我将它与 SQLite、MySQL、PostgreSQL 一起使用。太棒了。

      这可以使您摆脱这种语法错误,因为 SQL 确实将逗号和引号视为重要。

      对于硬编码,你可以试试这个:

      sql = """
      UPDATE fieldmap
      SET buildtype = '%s', buildlevel = 3
      WHERE rowid = 11
      """  % (house)
      

      这可以暂时解决您的问题,但不能长期解决。 ORM 是你的朋友。

      希望这会有所帮助!

      【讨论】:

      • 从不在传递到数据库的 SQL 命令中使用 %sstr.format。容易被SQL注入。
      • @aim100k 是的,我们知道。这就是我们使用 ORM 而不是硬编码的原因。然而,最关心注入的人会使用自己的 SQL ORM,而不是使用 SQLAlchemy。
      • @dotslash 寒心,我只是在暗示使用 sqlite3 提供的 ? 语法。另外,如果你不是心胸狭窄,可以搜索orm is an anti-pattern,我觉得新的视角还是有一些优点的
      猜你喜欢
      • 1970-01-01
      • 2014-01-22
      • 1970-01-01
      • 1970-01-01
      • 2014-12-26
      • 2018-06-23
      • 2018-04-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多