Middle
How can SQL injections be protected against?
sobes.tech AI
Answer from AI
To protect against SQL injection in Go, it is recommended to use prepared statements and parameterized queries, which separate SQL code from user data. This prevents the possibility of malicious SQL code injection.
Example using the database/sql package:
stmt, err := db.Prepare("SELECT * FROM users WHERE username = ?")
if err != nil {
// handle error
}
rows, err := stmt.Query(username)
// work with the result
It is also important to:
- Do not construct SQL queries by concatenating strings with user input.
- Use ORM or libraries that automatically parameterize queries.
- Limit database user permissions.
- Validate and filter input data.
These measures significantly reduce the risk of SQL injection.