Home >Backend Development >Python Tutorial >How Can I Safely Use Variables in SQL Queries Within Python?
Using Variables in SQL Statements in Python
When dealing with SQL statements in Python, you may need to incorporate variables into your queries. To ensure the correct execution of these queries, it's crucial to avoid including variable names as part of the SQL text itself.
Example Scenario:
Consider the following code:
cursor.execute("INSERT INTO table VALUES var1, var2, var3")
where var1 is an integer, and var2 and var3 are strings. This approach will result in an error because Python will interpret the variable names as part of the query, leading to an invalid SQL statement.
Solution:
To resolve this, you should use placeholders in your SQL statement and pass the variable values as a tuple using the execute() method. Here's the corrected code:
cursor.execute("INSERT INTO table VALUES (%s, %s, %s)", (var1, var2, var3))
In this example, the placeholders %s represent the variable values, and the tuple (var1, var2, var3) contains the actual values that should be inserted into the database.
Note: It's essential to use a tuple to pass multiple parameters. If you need to pass a single parameter, you must still use a tuple with a trailing comma:
cursor.execute("INSERT INTO table VALUES (%s)", (var1,))
Benefits:
Using placeholders and tuples provides several benefits:
The above is the detailed content of How Can I Safely Use Variables in SQL Queries Within Python?. For more information, please follow other related articles on the PHP Chinese website!