【问题标题】:Flask/MySQL WHERE IN clause not working with just one entryFlask/MySQL WHERE IN 子句不能仅使用一个条目
【发布时间】:2012-05-15 12:51:36
【问题描述】:

我有一个网站,它从复选框获取用户输入并从 MySQL 表中返回相应的行。

例如,用户可以选择几种颜色,网站将显示表格中具有该颜色的对象。

问题是当用户只选择一种颜色时,MySQL 查询没有正确创建,我得到一个错误。注意下面的colors 数组:

所以这行得通:

import MySQLdb
db = MySQLdb.connect(host="...", user="...", port=..., db="...", passwd="...")
colors = ["red", "blue"]
cursor.execute("SELECT * FROM `objects` WHERE `color` IN %s",(colors,))

这不是:

import MySQLdb
db = MySQLdb.connect(host="...", user="...", port=..., db="...",passwd="...")
colors = ["red"]
cursor.execute("SELECT * FROM `objects` WHERE `color` IN %s", (colors,))

有没有办法纠正这个问题?现在,我暂时添加了一种虚假的“颜色”(在数据库中没有与之关联的对象),但这显然不是一个理想的解决方案。

【问题讨论】:

  • IN 应该有括号...IN (%s)
  • @MarcB 当我这样做时,我收到以下错误:“1064,”您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 1 行的 '))' 附近使用正确的语法""
  • 这将有助于查看 MySQL 看到的查询(来自服务器日志)。无论如何,这个答案可能会有所帮助:stackoverflow.com/questions/4574609/…

标签: python mysql where-clause flask where-in


【解决方案1】:

您可以使用 .join 运算符。

colors = ["red", "blue"]
colors = ",".join(colors)

output:'red,blue'

colors = ["red"]
colors = ",".join(colors)

output: 'red'

所以代码看起来像

import MySQLdb as mdb
con = mdb.connect('', '','','')
with con:
    cur = con.cursor(mdb.cursors.DictCursor)
    colors = ["red","blue"]
    query = """SELECT * FROM objects where color in (""" + ",".join(colors) + """)
    cur.execute(users_query)
    rows = cur.fetchall()

【讨论】:

    【解决方案2】:

    你应该确认你的 MySQLdb egg 版本, 我之前遇到过这个问题,这个库使用 connection.literal(o) 来处理这样的 sql 值:

    sql = "select * from test where id in %s"
    sql_val = [100]
    # get connection and cur 
    cur.execute(sql, tuple([sql_val]))
    # see the last query sql 
    cur._last_executed
    
    # version MySQL_python-1.2.3c1-py2.6-linux-x86_64.egg execute exception and the query sql is:
    # attention to the last comma after '100' 
    select * from test where id in ('100',)
    
    # version MySQL_python-1.2.3c1-py2.6-linux-x86_64.egg execute successfully and the query sql is:
    # have no comma after '100' now 
    select * from test where id in ('100')
    

    所以,也许你应该将你的 MySQLdb egg 升级到最新版本来修复它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-07
      • 2012-06-16
      • 2012-07-19
      • 2010-10-09
      相关资源
      最近更新 更多