2012-05-06 21 views
1

我有一个网站,它从复选框获取用户输入并从MySQL表中返回相应的行。Flask/MySQL WHERE IN子句不能用于一个条目

例如,用户可以选择一对颜色,网站将显示表格中那些颜色的对象。

问题是,当用户只选择一种颜色的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,)) 

是否有办法来纠正呢?目前,我暂时添加了一个虚假的“颜色”(数据库中没有链接任何对象),但这显然不是一个理想的解决方案。

+0

'IN'应该有括号...'IN(%s)'。 –

+0

@MarcB当我这样做时,我得到以下错误:“1064,”你的SQL语法有错误;检查与您的MySQL服务器版本相对应的手册,在第1行'))'处使用正确的语法“ –

+0

这将有助于查看MySQL查看(从服务器日志中)的查询。无论如何,这个答案可能有所帮助:http://stackoverflow.com/questions/4574609/executing-select-where-in-using-mysqldb –

回答

0

您可以使用.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() 
0

你应该确认MySQLdb的鸡蛋, 的版本我以前见过这个问题,这个库使用connection.literal(O)来处理SQL vaules像那:

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蛋到最新的版本来解决它。