Principal
What is SQL injection and how to prevent it?
sobes.tech AI
Answer from AI
SQL injection is a type of vulnerability where an attacker inserts malicious SQL code into database queries through user input. This can lead to unauthorized access, modification, or deletion of data.
The following methods are used to combat SQL injections:
- Using parameterized queries (prepared statements) — parameters are passed separately from the SQL code, preventing execution of malicious code.
- Validation and filtering of user input — checking data for compliance with the expected format.
- Using ORM — many ORMs automatically protect against SQL injections.
- Minimizing database access rights — restricting the rights of the database user used by the application.
Example in SQL with a parameterized query (for example, in Python with the sqlite3 library):
cursor.execute("SELECT * FROM users WHERE username = ?", (username,))
Here, username is passed as a parameter, which excludes the possibility of injection.