There are several best practices to secure SQL database access and prevent SQL injection attacks in Go:
stmt, err := db.Prepare("SELECT * FROM users WHERE id = ?")
rows, err := stmt.Query(userID)
defer stmt.Close()
rows, err := db.Query("SELECT * FROM users WHERE name = ?", userName)
import "github.com/asaskevich/govalidator"
sanitizeName := func(name string) string {
return govalidator.EscapeSQL(name)
}
userName := sanitizeName(userProvidedInput)
rows, err := db.Query("SELECT * FROM users WHERE name = ?", userName)
Least Privilege Principle: Create a dedicated user with limited database privileges for your Go application. The user should only have the necessary permissions required to perform its tasks, reducing the impact of any potential SQL injection attacks.
Database Driver Support: Ensure you are using a well-maintained and secure SQL database driver for Go, such as "database/sql" or a third-party library with good security practices.
Avoid Dynamic SQL: Whenever possible, avoid constructing dynamic SQL queries using string concatenation. Use ORMs (Object Relational Mappers) like GORM, SQLBoiler, or Storm for database interaction, as they provide additional layers of security.
type User struct {
ID int64
Name string
// ...
}
var user User
db.Find(&user, "name = ?", userName)
db, err := sql.Open("mysql", "user:password@tcp(127.0.0.1:3306)/database")
Remember, incorporating these practices greatly reduces the risk of SQL injection attacks, but it's important to remain vigilant and follow security best practices throughout your codebase.