Home > Database > Mysql Tutorial > Can I Execute Parameterized SQL Queries Stored in a Variable in Python?

Can I Execute Parameterized SQL Queries Stored in a Variable in Python?

Susan Sarandon
Release: 2025-01-12 08:32:42
Original
593 people have browsed it

Can I Execute Parameterized SQL Queries Stored in a Variable in Python?

Execute parameterized SQL queries from variables in Python

To prevent SQL injection, when executing parameterized SQL queries in Python, it is generally recommended to use the following format:

cursor.execute("INSERT INTO table VALUES (%s, %s, %s)", var1, var2, var3)
Copy after login

However, it is worth exploring the question of whether it is possible to store the query in a variable and execute it later.

execute() Method signature

To understand why this might not work, we need to check the signature of the execute() method:

cursor.execute(self, query, args=None)
Copy after login

This method requires up to three parameters: a query and an optional parameter sequence or map.

Try to execute query from variable

If we try to execute a query stored in variable sql, for example:

sql = "INSERT INTO table VALUES (%s, %s, %s)"
cursor.execute(sql)
Copy after login

We will get an error because sql contains four parameters, including the variable itself.

Separate queries and parameters

To execute a query from a variable, we can separate the query and parameters:

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

In this case, sql contains the query and args contains the parameters. By specifying execute(sql, args), we can successfully execute the parameterized query.

Another way

Alternatively, we can use the more intuitive two-variable approach:

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

This approach eliminates the need to create separate variables for queries and parameters.

The above is the detailed content of Can I Execute Parameterized SQL Queries Stored in a Variable in Python?. For more information, please follow other related articles on the PHP Chinese website!

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