SQL Injection Prevention: Complete Guide with Code Examples
On this page
What is SQL Injection?
SQL injection is one of the most critical web vulnerabilities, affecting 39% of web applications according to OWASP. It occurs when an attacker inserts malicious SQL code into input fields, allowing them to manipulate database queries.
Real-World Impact
- Target (2013): Lost 40 million credit card numbers via SQL injection
- Healthcare.gov (2015): Exposed 21 million ID numbers
- Equifax (2017): 147 million records compromised
Types of SQL Injection
1. Error-Based SQL Injection
Displays database errors to extract information.
Example SQL:
SELECT * FROM users WHERE username = 'admin' AND password = 'pass'
-- Attack: admin' OR '1'='1
-- Result: Bypasses authentication
2. Union-Based SQL Injection
Merges attacker's query with original query to extract data.
3. Blind SQL Injection
No direct error feedback. Attacker infers data via response times/behavior.
4. Stacked Queries
Executes multiple SQL statements (if supported by database).
Prevention Methods
Method 1: Parameterized Queries (BEST)
Use parameter placeholders instead of string concatenation.
Python Example:
cursor.execute("SELECT * FROM users WHERE id = ?", (user_id,))
Node.js Example:
connection.query('SELECT * FROM users WHERE id = ?', [userId])
Java Example:
PreparedStatement stmt = connection.prepareStatement("SELECT * FROM users WHERE id = ?");
stmt.setString(1, userId);
ResultSet rs = stmt.executeQuery();
Method 2: Input Validation
Validate all user inputs server-side:
- Allowlist expected characters
- Enforce data types
- Limit input length
Method 3: Web Application Firewall
Deploy WAF rules to detect SQL injection patterns:
SecRule ARGS "@rx (?i:union.*select|select.*from|insert.*into|delete)"
Method 4: Least Privilege Database Users
Create database users with minimal necessary permissions:
CREATE USER 'app_user'@'localhost' IDENTIFIED BY 'strong_password';
GRANT SELECT, INSERT, UPDATE ON database.* TO 'app_user'@'localhost';
-- Never grant DROP, ALTER, or administrative privileges
Detection & Testing
Using OWASP ZAP
OWASP ZAP automatically scans for SQL injection vulnerabilities.
Using SQLMap
Command-line tool for detecting SQL injection:
sqlmap -u "http://target.com/page?id=1" --dbs
Manual Testing Payloads
' OR '1'='1admin' --1 UNION SELECT NULL, NULL' AND SLEEP(5) --
SQL Injection Prevention Checklist
- Use parameterized queries exclusively
- Implement server-side input validation
- Use ORMs when possible (Sequelize, Hibernate, SQLAlchemy)
- Apply principle of least privilege to DB users
- Enable SQL error suppression in production
- Deploy Web Application Firewall
- Implement comprehensive logging
- Regular penetration testing
- Security code reviews
- Keep database software updated
Key Takeaways
- Always use parameterized queries - No exceptions, no concatenation
- Input validation is NOT enough - Use as defense-in-depth only
- Database user permissions matter - Limit what app can do
- Monitor for suspicious activity - Detection is critical
- Test regularly - Automated + manual testing essential
Resources
- OWASP SQL Injection: https://owasp.org/www-community/attacks/SQL_Injection
- CWE-89: SQL Injection
- PortSwigger SQL Injection Guide
- NIST Secure Coding Standards
Published by SecureCodeReviews
This article is part of our original AI security and cybersecurity content library. We show publish and update dates, keep company and policy pages public, and update important guidance when material changes affect readers.
Want an expert review before this issue reaches production?
We combine manual code review with AppSec tooling to find vulnerabilities, logic flaws, and insecure patterns before release or audit deadlines.
Advertisement
Free Security Tools
Try our tools now
Expert Services
Get professional help
OWASP Top 10
Learn the top risks
Related Articles
OWASP Top 10 2025: What's Changed and How to Prepare
A comprehensive breakdown of the latest OWASP Top 10 vulnerabilities and actionable steps to secure your applications against them.
XSS (Cross-Site Scripting) Prevention: Complete Guide 2025
Learn to prevent Stored, Reflected, and DOM-based XSS attacks. Includes real examples, OWASP prevention strategies, and Content Security Policy implementation.
Top 5 SQL Injection Mistakes in Django Apps (And How to Fix Them)
Django's ORM is safe by default — but developers still introduce SQL injection through raw queries, extra(), and cursor.execute(). Here are the 5 most common mistakes we find in real code reviews.