The text below is selected, press Ctrl+C to copy to your clipboard. (⌘+C on Mac) No line numbers will be copied.
Guest
Python how to prevent sql injection sample code with SQLite and parameterized queries
By Guest on 9th December 2022 08:50:29 PM | Syntax: PYTHON | Views: 187



New Paste New paste | Download Paste Download | Toggle Line Numbers Show/Hide line no. | Copy Paste Copy text to clipboard
  1. To prevent SQL injection in Python, you can use the "parameterized queries" feature in Python's database API. This allows you to specify placeholders in your SQL query, and then provide the actual values as separate parameters. This ensures that the values are treated as data and not part of the SQL query, which protects against SQL injection attacks.
  2.  
  3. Here is an example of how to use parameterized queries in Python to prevent SQL injection:
  4.  
  5. Copy code
  6. # Import the database API module
  7. import sqlite3
  8.  
  9. # Connect to the database
  10. db = sqlite3.connect("database.db")
  11.  
  12. # Create a cursor object
  13. cursor = db.cursor()
  14.  
  15. # Define the SQL query with placeholders
  16. query = "SELECT * FROM users WHERE username = ? AND password = ?"
  17.  
  18. # Provide the actual values as separate parameters
  19. cursor.execute(query, ("johnsmith", "password123"))
  20.  
  21. # Fetch the results
  22. results = cursor.fetchall()
  23.  
  24. # Loop through the results and print them
  25. for row in results:
  26.    print(row)
  27.  
  28. # Close the cursor and the database connection
  29. cursor.close()
  30. db.close()
  31.  
  32.  
  33. In this example, the values for the username and password are provided as separate parameters, rather than being included directly in the SQL query. This protects against SQL injection attacks, as the values are treated as data.
















Python software and documentation are licensed under the PSF License Agreement.
Starting with Python 3.8.6, examples, recipes, and other code in the documentation are dual licensed under the PSF License Agreement and the Zero-Clause BSD license.
Some software incorporated into Python is under different licenses. The licenses are listed with code falling under that license. See Licenses and Acknowledgements for Incorporated Software for an incomplete list of these licenses.

Python and it's documentation is:
Copyright © 2001-2022 Python Software Foundation. All rights reserved.
Copyright © 2000 BeOpen.com. All rights reserved.
Copyright © 1995-2000 Corporation for National Research Initiatives. All rights reserved.
Copyright © 1991-1995 Stichting Mathematisch Centrum. All rights reserved.

See History and License for complete license and permissions information:
https://docs.python.org/3/license.html#psf-license
  • Recent Pastes