SQL injection attacks occur when malicious code is inserted into an SQL query, allowing attackers to read or modify data in a database. They work by exploiting insecure code that fails to properly sanitize user input. To prevent SQL injection, developers should escape quotes, remove dangerous characters from queries, limit user privileges and access, and validate all user-provided data.