Python, Mysql에서 in 조건문 사용 방법

Photo by Caspar Camille Rubin on Unsplash

환경

Python 3.8

mysql-connector-python 8.0.26

요약

where 조건절에 in 조건문이 있는 경우에는 쿼리를 동적으로 작성해야 한다. 

왜냐하면 in 구문에 들어가야 할 %s-markers 갯수가 매번 달라질 수 있기 때문이다. 


구현

query_params = .....
 
sql = 'select col1, col2  ' \
      'from table1 ' \
      'where area in ( %s ) '
 
conn = db_pool.get_connection()
curs = conn.cursor()
 
format_strings = ','.join(['%s'* len(query_params))
 
curs.execute(sql % format_strings, tuple(query_params))
cs


참조

https://stackoverflow.com/questions/17847297/mysql-connector-python-in-operator-stored-as-list


댓글 쓰기

0 댓글