Home > Database > Mysql Tutorial > body text

How to Execute \'SELECT ... WHERE ... IN ...\' Queries with MySQLdb in Python?

DDD
Release: 2024-11-02 17:19:29
Original
545 people have browsed it

How to Execute

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

In Python, executing SQL queries involving the "IN" clause using MySQLdb can encounter challenges. Consider the following scenario:

Problem:

Attempting to execute a query like this:

<code class="sql">SELECT fooid FROM foo WHERE bar IN ('A','C');</code>
Copy after login

from within Python using the following code:

<code class="python">import MySQLdb
import config
connection=MySQLdb.connect(
    host=config.HOST,user=config.USER,passwd=config.PASS,db='test')
cursor=connection.cursor()

sql='SELECT fooid FROM foo WHERE bar IN %s'
args=[['A','C']]
cursor.execute(sql,args)
data=cursor.fetchall()
print(data)
# ()</code>
Copy after login

results in an empty dataset, despite the expectation of two rows.

Cause:

MySQLdb automatically adds single quotes around elements in the input list args, resulting in the query being executed as:

<code class="sql">SELECT fooid FROM foo WHERE bar IN ("'A'", "'C'")</code>
Copy after login

This query differs from the original intended query, which used a single-quoted list.

Solution:

To overcome this issue, you must manually construct the query parameters. Here's a modified version of the Python code that addresses the problem:

<code class="python">import MySQLdb
import config
connection=MySQLdb.connect(
    host=config.HOST,user=config.USER,passwd=config.PASS,db='test')
cursor=connection.cursor()

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)
data=cursor.fetchall()
print(data)
# (('1',), ('3',))</code>
Copy after login

By constructing the in_p string using map() and joining it with commas, you effectively create a series of placeholders for the elements in args. The use of the % operator ensures that the placeholders are correctly substituted with the actual values when the query is executed.

The above is the detailed content of How to Execute \'SELECT ... WHERE ... IN ...\' Queries with MySQLdb in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!