Home > Database > Mysql Tutorial > How to Prevent SQL Injection When Updating an SQLite Database via JSON POST in Python?

How to Prevent SQL Injection When Updating an SQLite Database via JSON POST in Python?

DDD
Release: 2025-01-04 21:35:41
Original
848 people have browsed it

How to Prevent SQL Injection When Updating an SQLite Database via JSON POST in Python?

SQL Injection Protection in Python

Question:

To protect against SQL injection vulnerability, how can a string received from the user and sent via JSON POST be sanitized for safe update operations in an SQLite database within Python?

Answer:

Utilizing Parameterized Queries

The recommended approach to mitigate SQL injection risk is to use parameterized queries. Python's sqlite3 module supports this via placeholder parameters (?). Instead of concatenating user input directly into the SQL statement, it is passed as a parameter, separating user input from SQL syntax.

Revised Code:

def setLabel(self, userId, refId, label):
    cursor = self._db.cursor()
    query = """UPDATE items SET label = ? WHERE userId IS ? AND refId IS ?"""
    cursor.execute(query, (label, userId, refId))
    self._db.commit()
Copy after login

By using a parameterized query, any potentially malicious characters or metacharacters in the label input are automatically escaped, ensuring they are interpreted as literal text rather than SQL commands.

The above is the detailed content of How to Prevent SQL Injection When Updating an SQLite Database via JSON POST in 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template