Home >Database >Mysql Tutorial >How Can I Effectively Execute Parameterized SQL Queries in Python Using Variables?
Storing SQL queries in variables improves code flexibility and readability. This article explores how to leverage variables to efficiently execute parameterized SQL queries in Python.
Parameterized SQL queries prevent SQL injection by separating SQL statements from variable data. In Python, this is achieved through the cursor.execute()
method, where the placeholder (%s) represents the variable.
To store the SQL query in a variable, assign it to a string variable, for example:
<code class="language-python">sql = "INSERT INTO table VALUES (%s, %s, %s)"</code>
To perform a parameterized query with multiple variables, pass the variables as a sequence or map. However, the execute()
method expects three parameters, and containing a SQL query exceeds this limit.
To solve this problem, SQL queries and variables can be split into separate variables and parameters. One way is to assign the variable to the element of the tuple:
<code class="language-python">sql_and_params = ("INSERT INTO table VALUES (%s, %s, %s)", var1, var2, var3)</code>
However, this method throws an error due to the number of parameters. Instead, when passing it to execute()
, the tuple should be split as follows:
<code class="language-python">cursor.execute(sql_and_params[0], sql_and_params[1:])</code>
A more readable approach is to use separate variables for the SQL query and its parameters:
<code class="language-python">sql = "INSERT INTO table VALUES (%s, %s, %s)" args = var1, var2, var3 cursor.execute(sql, args)</code>
This method provides a clear separation between the SQL statement and its parameters.
The above is the detailed content of How Can I Effectively Execute Parameterized SQL Queries in Python Using Variables?. For more information, please follow other related articles on the PHP Chinese website!