How can I write an SQL IN query with a Python tuple?

PythonProgramming

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.

raja
Published on 18-Apr-2018 11:30:26
Advertisements