"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > MySQLdb SELECT ... WHERE ... IN ... Why is the query resultless?

MySQLdb SELECT ... WHERE ... IN ... Why is the query resultless?

Posted on 2025-04-16
Browse:328

Why Doesn\'t My MySQLdb SELECT ... WHERE ... IN ... Query Return Results?

Executing "SELECT ... WHERE ... IN ..." Using MySQLdb

When executing an SQL query with an IN clause using MySQLdb, it's important to pay attention to how the query parameters are constructed.

Problem

A user encountered an issue while trying to select fooids where bar was in ('A','C') using Python and MySQLdb. Despite the identical query working from the mysql command-line, it returned no rows in Python.

Root Cause

The issue arose because MySQLdb converted the parametrized argument ['A','C'] to ("'A'","'C'"), which resulted in too many quotes around the values in the IN clause.

Solution

To execute the query correctly, the query parameters must be manually constructed. The following Python code demonstrates how to achieve this:

Python 3:

args = ['A', 'C']
sql = 'SELECT fooid FROM foo WHERE bar IN (%s)'
in_p = ', '.join(list(map(lambda x: '%s', args)))
sql = sql % in_p
cursor.execute(sql, args)

Python 2:

args = ['A', 'C']
sql = 'SELECT fooid FROM foo WHERE bar IN (%s)'
in_p = ', '.join(map(lambda x: '%s', args))
sql = sql % in_p
cursor.execute(sql, args)
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3