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 using parameterized queries
By Guest on 9th December 2022 08:45:57 PM | Syntax: PYTHON | Views: 183



New Paste New paste | Download Paste Download | Toggle Line Numbers Show/Hide line no. | Copy Paste Copy text to clipboard
  1. Here is an example of how to prevent SQL injection in Python using parameterized queries:
  2.  
  3.  
  4. import mysql.connector
  5.  
  6. # connect to the database
  7. db = mysql.connector.connect(
  8.     host="localhost",
  9.     user="user",
  10.     password="password",
  11.     database="database"
  12. )
  13.  
  14. # prepare a cursor object
  15. cursor = db.cursor()
  16.  
  17. # define the SQL query with placeholders for the parameters
  18. query = "SELECT * FROM users WHERE username=%s AND password=%s"
  19.  
  20. # get the user-supplied values for the parameters
  21. username = input("Enter your username: ")
  22. password = input("Enter your password: ")
  23.  
  24. # execute the query using the user-supplied values as parameters
  25. cursor.execute(query, (username, password))
  26.  
  27. # fetch and process the result set
  28. result = cursor.fetchone()
  29. if result:
  30.     print("Welcome, {}!".format(username))
  31. else:
  32.     print("Invalid username or password")
  33.  
  34. # close the cursor and database connection
  35. cursor.close()
  36. db.close()
















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