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.

Updated on: 05-Mar-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements