【问题标题】:Error in SQL syntax while querying in MariaDB在 MariaDB 中查询时 SQL 语法错误
【发布时间】:2016-03-25 20:31:48
【问题描述】:

我在 ma​​riadb 中有一个名为 Container 的表,其中包含三个字段 container_idmt_dateage

我想要做的是,每次加载数据库时,更新/设置与特定 container_id 对应的年龄字段的新值。我将年龄和相应的 container_id 分别保存在 python 字典中作为值和键。比我遍历字典并尝试像这样更新 age -

for i in list(age_dict):
    frappe.db.sql("update Container set age = age_dict[i] where container_id = i")

这里,frappe.db.sql() 是我的框架的数据库连接命令。

我不断收到此错误消息-

ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '[i] where container_id = i' at line 1")

我已经检查了我的 sql 查询代码几次,但找不到语法错误。寻求帮助。

【问题讨论】:

    标签: python mariadb mariasql


    【解决方案1】:

    您在 SQL 语句中的 Python 代码永远不会被解释。数据库实际上是在尝试执行命令update Container set age = age_dict[i] where container_id = i,这确实是无效的语法。您应该使用参数化,这将有助于防止 SQL 注入并轻松格式化 SQL 命令。语法几乎与字符串插值相同,但您将值(作为元组)作为第二个参数传递给frappe.db.sql()

    for key in list(age_dict):
        frappe.db.sql(
            "update Container set age = %s where container_id = %s",
            (age_dict[key], key)
        )
    

    【讨论】:

    • 还值得指出的是,for 循环最好写成for key in age_dict:,因为先将其键转换为列表没有任何好处。
    • 我将其转换为列表以保留字典的状态。可能在我的查询中,没关系,但如果我错误地尝试删除一个键,至少它不会使我的代码崩溃。
    • @ni8mr:如果你的意思是你不小心在循环中执行了del key,它不会有任何区别。无论哪种方式,您都将使用对实际字典持有的键的引用。删除该引用不会删除实际的键,因为字典仍会保存对它的引用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-19
    • 2011-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-10
    相关资源
    最近更新 更多