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!