Home > Database > Mysql Tutorial > How to Safely Insert Variables into SQL Statements from Python?

How to Safely Insert Variables into SQL Statements from Python?

Linda Hamilton
Release: 2025-01-25 15:27:11
Original
262 people have browsed it

How to Safely Insert Variables into SQL Statements from Python?

Use variables in SQL statements in Python code

In order to insert variables in a SQL statement written in Python, the parameters must be represented in a specific way to prevent them from being included as part of the query text itself. The correct syntax involves using placeholders and passing variables as tuples.

Consider the following Python code example:

<code class="language-python">cursor.execute("INSERT INTO table VALUES var1, var2, var3")</code>
Copy after login

Where var1 is an integer, var2 and var3 are strings.

To combine these variables in Python without including them as part of the query text, use the following syntax:

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

The key difference here is using placeholders (%s) in the SQL statement and passing variables as tuples (enclosed in parentheses). The database API handles escaping and quoting automatically, ensuring data is safely incorporated into queries.

Avoid using the string formatting operator (%) to pass variables directly as it skips any necessary escaping or quoting, leaving the code vulnerable to attacks such as SQL injection.

The above is the detailed content of How to Safely Insert Variables into SQL Statements from Python?. 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