Home >Database >Mysql Tutorial >How Can I Prevent SQL Injection Attacks When Using SQLite in Python?

How Can I Prevent SQL Injection Attacks When Using SQLite in Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-04 19:12:39822browse

How Can I Prevent SQL Injection Attacks When Using SQLite in Python?

Protecting Against SQL Injection in Python

When fetching data from untrusted sources, such as user input, it's crucial to prevent SQL injection attacks. In Python, using SQLite, you can effectively protect your database using the cursor's execute() method.

Consider the following code snippet:

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

In this example, the label is obtained from the user and directly inserted into the SQL query. This exposes vulnerabilities to SQL injection attacks.

To secure the operation, use the execute() method with parameters as follows:

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

Parameters are automatically escaped by SQLite and included in the query. This prevents attackers from injecting malicious code into your database. By embracing this method, you can effectively safeguard your application against SQL injection attacks.

The above is the detailed content of How Can I Prevent SQL Injection Attacks When Using SQLite in 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