2012-05-06 6 views
1

나는 사용자 입력을 체크 박스에서 얻고 MySQL 테이블에서 해당 행을 반환하는 웹 사이트를 가지고있다.Flask/MySQL WHERE IN 절이 단 하나의 엔트리와 작동하지 않는다

예를 들어 사용자는 몇 가지 색상을 선택할 수 있으며 웹 사이트는 해당 색상 인 표의 개체를 표시합니다.

문제는 사용자가 하나의 색만 선택하면 MySQL 쿼리가 제대로 만들어지지 않고 오류가 발생하는 것입니다.

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,)) 

이 문제를 해결하는 방법이 있나요 아래 colors 배열이 있습니다? 지금은 일시적으로 가짜 "색"(데이터베이스에 연결된 개체가없는 색)을 추가하고 있지만 이는 분명히 이상적인 솔루션이 아닙니다.

+0

'IN'에는 대괄호 ... '(% s)'가 있어야합니다. –

+0

@MarcB 다음과 같은 오류가 발생합니다. "1064"SQL 구문에 오류가 있습니다. ') 1'at " –

+0

근처에있는 올바른 구문을 찾으려면 MySQL 서버 버전에 해당하는 설명서를 확인하십시오. 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

당신은,이 라이브러리는 SQL vaules 등으로 처리 connection.literal (O)를 사용 내가 전에이 질문을 만났다 MySQLdb 달걀, 의 버전을 확인해야합니다 그 :

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 계란을 업그레이 드해야합니다.

관련 문제