Home >Backend Development >Python Tutorial >How Can I Safely Use Variables in SQL Statements within Python?

How Can I Safely Use Variables in SQL Statements within Python?

Linda Hamilton
Linda HamiltonOriginal
2025-01-01 09:03:10975browse

How Can I Safely Use Variables in SQL Statements within Python?

Using Variables in SQL Statements in Python

This article provides a solution to the common issue of using variables in SQL statements in Python. The following Python code:

cursor.execute("INSERT INTO table VALUES var1, var2, var3")

will fail with an error because the variable names are included as part of the query text. To resolve this, use the following syntax:

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

In this solution, the variable names are replaced with placeholders (%s) in the SQL statement. The parameters are then passed as a tuple, (var1, var2, var3). Note that the tuple must end with a comma if you are passing a single parameter.

Using this method ensures that the database API handles proper escaping and quoting of variables. It is important to avoid using the string formatting operator %, as it does not perform any escaping or quoting. This can lead to security vulnerabilities such as SQL injection.

The above is the detailed content of How Can I Safely Use Variables in SQL Statements within Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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