Senior
How have you worked with PostgreSQL? How do you protect against SQL injections?
sobes.tech AI
Answer from AI
To work with PostgreSQL in Go, the database/sql package is usually used along with a driver, such as lib/pq or pgx. The main way to protect against SQL injection is by using prepared statements and parameterized queries. Instead of concatenating strings with parameters, parameters are passed separately, allowing the driver to correctly escape the values.
Example:
query := `SELECT * FROM users WHERE email = $1`
row := db.QueryRow(query, userEmail)
Here, $1 is a placeholder, and userEmail is a parameter that the driver safely substitutes into the query.
It is also important to avoid dynamically constructing SQL with strings, especially with user data, and to use an ORM or query builder that automatically handles parameters.