Use variables in SQL statements in Python code
In order to insert variables in a SQL statement written in Python, the parameters must be represented in a specific way to prevent them from being included as part of the query text itself. The correct syntax involves using placeholders and passing variables as tuples.
Consider the following Python code example:
<code class="language-python">cursor.execute("INSERT INTO table VALUES var1, var2, var3")</code>
Where var1 is an integer, var2 and var3 are strings.
To combine these variables in Python without including them as part of the query text, use the following syntax:
<code class="language-python">cursor.execute("INSERT INTO table VALUES (%s, %s, %s)", (var1, var2, var3))</code>
The key difference here is using placeholders (%s) in the SQL statement and passing variables as tuples (enclosed in parentheses). The database API handles escaping and quoting automatically, ensuring data is safely incorporated into queries.
Avoid using the string formatting operator (%) to pass variables directly as it skips any necessary escaping or quoting, leaving the code vulnerable to attacks such as SQL injection.
The above is the detailed content of How to Safely Insert Variables into SQL Statements from Python?. For more information, please follow other related articles on the PHP Chinese website!