- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
- Python Advanced Tutorial
- Python - Classes/Objects
- Python - Reg Expressions
- Python - CGI Programming
- Python - Database Access
- Python - Networking
- Python - Sending Email
- Python - Multithreading
- Python - XML Processing
- Python - GUI Programming
- Python - Further Extensions
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,
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
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.
- Related Articles
- How can I convert a Python tuple to an Array?
- How can I append a tuple into another tuple in Python?
- How can I subtract tuple of tuples from a tuple in Python?
- How can I use Multiple-tuple in Python?
- How can I define duplicate items in a Python tuple?
- How I can dump a Python tuple in JSON format?
- How can I do Python Tuple Slicing?
- How I can convert a Python Tuple into Dictionary?
- How can I convert a Python tuple to string?
- How can I create a non-literal python tuple?
- How can I represent python tuple in JSON format?
- How can I convert Python strings into tuple?
- How can I create a Python tuple of Unicode strings?
- How can I remove items out of a Python tuple?
- How can I convert a Python Named tuple to a dictionary?