Using variables in SQL statements in Python
When working with SQL statements in Python, it is important to pay attention to how variables are integrated into the query. In the provided Python code, there is a query that needs to insert the variables var1, var2, and var3 into a SQL table. The problem is to avoid interpreting the variables as part of the query text.
To solve this problem, the execute()
method provides a mechanism to pass variables as tuples. The modified code is as follows:
<code class="language-python">cursor.execute("INSERT INTO table VALUES (%s, %s, %s)", (var1, var2, var3))</code>
Please note:
(var1, var2, var3)
. (a,)
. The database API handles proper escaping and quoting of variables. However, it is crucial to avoid using the string formatting operator (%) for the following reasons:
The above is the detailed content of How to Safely Insert Variables into SQL Queries in Python?. For more information, please follow other related articles on the PHP Chinese website!