SQL Injection
SQL injection is an attack in which an attacker types specially crafted input into a form field, URL or API so that it changes the meaning of a database query the application builds. It happens when an application joins user input directly into SQL text, and it can let attackers read, change or delete data, or log in without a password.
The main defence is to use parameterised queries (prepared statements) or an ORM, so that input is always treated as data and never as SQL code. Other defences include validating input, giving the database account only the permissions it needs and hiding detailed error messages.
// Unsafe: input such as ' OR '1'='1 changes the query
String sql = "SELECT * FROM users WHERE email = '" + email + "'";
// Safe: the input is sent separately as a parameter
PreparedStatement ps = conn.prepareStatement("SELECT * FROM users WHERE email = ?");
ps.setString(1, email);
ResultSet rs = ps.executeQuery();