Home > Database > Mysql Tutorial > body text

How to Execute a SELECT Query with an IN Clause Using MySQLdb?

Barbara Streisand
Release: 2024-10-31 00:53:03
Original
118 people have browsed it

How to Execute a SELECT Query with an IN Clause Using MySQLdb?

Executing "SELECT ... WHERE ... IN ..." using MySQLdb

When attempting to execute a SELECT query with an IN clause using MySQLdb, users may encounter issues where no rows are returned despite the query working as expected from the mysql command-line. This can occur due to unnecessary quotes being placed around the IN values.

To overcome this issue, manual construction of the query parameters is required. In both Python 2 and 3, a comma-separated string of placeholders (%s) can be generated from the list of IN values. The query can then be formatted using this string and executed with the original list of values.

For Python 3:

<code class="python">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)</code>
Copy after login

For Python 2:

<code class="python">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)</code>
Copy after login

By following this approach, the SQL query will be correctly formatted with the desired IN values, resolving the issue where no rows were returned previously.

The above is the detailed content of How to Execute a SELECT Query with an IN Clause Using MySQLdb?. 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
Latest Articles by Author
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!