【问题标题】:a MySQL query error in PythonPython 中的 MySQL 查询错误
【发布时间】:2018-08-11 00:42:02
【问题描述】:

我在运行以下代码时遇到了 MySQL 语法错误:

cnx = mysql.connector.connect(**connection)
cursor = cnx.cursor()

select_categories = ("select `id`, `name`, `url` from categories where `id_parent`=%s")
cursor.execute( select_categories, (4) )

错误:

mysql.connector.errors.ProgrammingError: 1064 (42000): 你的 SQL 语法有错误;查看与您的 MySQL 服务器版本相对应的手册,了解在第 1 行的“%s”附近使用的正确语法

如何解决?

【问题讨论】:

  • 应该是"select id, name, url from categories where", id_parent=%s
  • @Maddy:不。如果我设置select_categories = ("select 'id', 'name', 'url' from categories where 'id_parent'=4") ,一切都会正常工作
  • 你的参数应该是序列。一个元素的元组是 (4,) 但你有 (4) 这是一个标量。
  • @Parfait:它有效。谢谢!!!

标签: python mysql


【解决方案1】:

问题是python将(4)解释为4,参数需要是可迭代的。尝试更新到这个:

cursor.execute( select_categories, (4, ) )

4 后面的逗号将强制 python 将其解释为元组。

【讨论】:

    猜你喜欢
    • 2016-07-21
    • 2016-08-05
    • 1970-01-01
    • 2013-11-01
    • 2011-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多