Home > Database > Mysql Tutorial > How to Safely Parameterize SQL SELECT Statements in Python with pyodbc?

How to Safely Parameterize SQL SELECT Statements in Python with pyodbc?

DDD
Release: 2025-01-03 12:58:38
Original
730 people have browsed it

How to Safely Parameterize SQL SELECT Statements in Python with pyodbc?

Parameterized Select Statements in Python Using pyodbc

This question discusses how to execute a SQL SELECT statement using a variable as a parameter in a loop over a table called "Throughput." The specific parameter used varies depending on the row's "DeviceName" attribute.

Initial Attempts

Initially, the user attempted the following code without success:

for row in cursor.execute("SELECT * FROM Throughput WHERE DeviceName=%s", %(data['DeviceName'])):
Copy after login

Another unsuccessful attempt was:

for row in cursor.execute("SELECT * FROM Throughput WHERE(DeviceName), values(?)", (data['DeviceName']) ):
Copy after login

Final Working Code

Ultimately, the user successfully resolved the issue with the following snippet:

query = "SELECT * FROM Throughput WHERE DeviceName = '%s'" % data['Device Name']
try:
    for row in cursor.execute(query):
Copy after login

Parameterized Statements

The recommended approach is to use parameterized statements:

cursor.execute("SELECT * FROM Throughput WHERE DeviceName = ?", data['DeviceName'])
Copy after login

This approach offers several advantages over the previous attempts:

  • Protection against SQL injection
  • No need to escape where clause values with single quotes
  • SQL preparation only occurs once, improving performance for subsequent executions

The above is the detailed content of How to Safely Parameterize SQL SELECT Statements in Python with pyodbc?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template