- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How can I write an SQL IN query with a Python tuple?
To write an SQL in query, you need to ensure that you provide the placeholders in the query using so that the query is properly escaped. For example,
Example
my_tuple = ("Hello", "world", "John") placeholder= '?' placeholders= ', '.join(placeholder for _ in my_tuple) query= 'SELECT name FROM students WHERE id IN (%s)' % placeholders print(query)
# now execute using the cursor
cursor.execute(query, my_tuple)
Output
This will give the output
'SELECT name FROM students WHERE id IN (?, ?, ?)'
And when you call to execute, it'll replace them? placeholders correctly by the escaped values.
Advertisements