Integrated variables in Python into SQL query
When using Python to perform SQL query, the variable is usually integrated into the query. For example, you may want to insert the data into the database table, and these values are stored in variables.
Question
Consider the following Python code:
Among them, VAR1 is an integer, VAR2 and VAR3 are string. When trying to write a variable name without letting Python use them as part of the query text, there will be problems.
<code class="language-python">cursor.execute("INSERT INTO table VALUES var1, var2, var3")</code>
In order to solve this problem, you can use the place occupies in the SQL query, and transmit the variable value as the meta -group:
Please note that the meta -group contains variable values. Even if only one parameter is passed, the comma must be added at the end of the Yuan group. This ensures that the database API corrects the variables and references correctly.Warning
<code class="language-python">cursor.execute("INSERT INTO table VALUES (%s, %s, %s)", (var1, var2, var3))</code>
Avoid using the string format format (%) for variable replacement, because it does not execute the righteousness or reference, and is easily injected with SQL into attack.
The above is the detailed content of How Can I Safely Incorporate Python Variables into SQL Queries?. For more information, please follow other related articles on the PHP Chinese website!