Junior — Middle
What methods are used to prevent vulnerabilities such as SQL injection when working with a database?
sobes.tech AI
Answer from AI
To prevent SQL injection in Go when working with databases, the following methods are used:
-
Parameterized queries (prepared statements) — instead of concatenating strings with SQL queries and data, parameters are used, which are passed separately. This prevents malicious code injection.
-
Using ORM or libraries that automatically escape data — for example, GORM.
-
Validation and sanitization of input data — although this does not replace parameterization, it helps reduce risks.
Example of a parameterized query using the standard library database/sql:
var username string
err := db.QueryRow("SELECT name FROM users WHERE id = ?", userID).Scan(&username)
if err != nil {
// handle error
}
Here, ? is a parameter that is safely substituted into the query, preventing injection.