Home > Database > Mysql Tutorial > How Can I Safely Use Variables in SQL Queries with Python's `cursor.execute()` Function?

How Can I Safely Use Variables in SQL Queries with Python's `cursor.execute()` Function?

Linda Hamilton
Release: 2025-01-12 08:20:43
Original
183 people have browsed it

How Can I Safely Use Variables in SQL Queries with Python's `cursor.execute()` Function?

Using variables in Python for parameterized SQL queries

In Python, parameterized SQL queries are crucial to prevent SQL injection. Although the recommended approach is to pass variables directly to the execute function, in some cases it is also desirable to use variables to represent the query itself.

Query as variable: syntax error

Trying to execute a SQL query directly from a variable (as shown below) results in a syntax error:

<code>sql = "INSERT INTO table VALUES (%s, %s, %s)", var1, var2, var3
cursor.execute(sql)</code>
Copy after login

Execute function

cursor.executeThe signature of the function specifies that it accepts up to three parameters:

<code>cursor.execute(self, query, args=None)</code>
Copy after login

Therefore, it is incorrect to pass a variable containing query and parameters as a single parameter.

Solution

To solve this problem, there are two possible solutions:

Tuple expanded with parameters:

<code>sql_and_params = "INSERT INTO table VALUES (%s, %s, %s)", var1, var2, var3
cursor.execute(*sql_and_params)</code>
Copy after login

However, this approach may cause errors if the tuple has more than three elements.

Separate query and parameters:

Alternatively, you can separate the query and parameters:

<code>sql = "INSERT INTO table VALUES (%s, %s, %s)"
args = var1, var2, var3
cursor.execute(sql, args)</code>
Copy after login

This method is more verbose, but ensures that the correct number of parameters are passed to the execute function.

The above is the detailed content of How Can I Safely Use Variables in SQL Queries with Python's `cursor.execute()` Function?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template