SQL Injection Explained: Risks, Examples, and Prevention
**SQL injection** happens when an application builds a database query by gluing user input directly into the SQL text. An attacker can then change what the query does. ## An unsafe example
String sql = "SELECT * FROM users WHERE username = '" + name + "' AND password = '" + pass + "'";If someone enters `' OR '1'='1` as the username, the query becomes:
SELECT * FROM users WHERE username = '' OR '1'='1' AND password = ''The condition is always true, so the login check can be bypassed. Worse inputs can read, change, or delete data. ## Why it works The database cannot tell which part of the string is your code and which part is the user's data. Both arrive as one piece of text. ## Prevention ### 1. Use parameterized queries
String sql = "SELECT * FROM users WHERE username = ? AND password_hash = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, name);
ps.setString(2, passHash);The input is sent separately from the SQL, so it is always treated as data. ### 2. Use least-privilege accounts The account your app uses should only have the permissions it needs. A web app rarely needs to drop tables or read system data. ### 3. Validate input Check length, type, and format. This is a helpful extra layer, but it does not replace parameterized queries. ### 4. Hide error details Never show raw database errors to visitors. Log them privately instead. ### 5. Hash passwords Even if data leaks, properly hashed passwords are much harder to misuse. ## Quick checklist - No string concatenation in SQL - Parameters everywhere user input appears - Database user with minimal rights - Generic error messages for visitors Small habits like these stop one of the most common attacks on web applications.