How can I prevent SQL injection attacks in Go while using "database/sql"?

As long as you're using Prepare or Query, you're safe.

// this is safe
db.Query("SELECT name FROM users WHERE age=?", req.FormValue("age"))
// this allows sql injection.
db.Query("SELECT name FROM users WHERE age=" + req.FormValue("age"))

I agree with @Oneonone's answer.

If you are retrieving data, do something like:

db.Query("SELECT name FROM users WHERE age=?", req.FormValue("age"))

If you have to insert a lot of data safely, using the same query, this is where Prepare comes handy. you can do something like this:

tx, err := db.Begin()
if err != nil {
    return nil,err
}
stmt, err := tx.Prepare("INSERT INTO users VALUES (?, ?)")
if err != nil {
    tx.Rollback()
    return nil,err
}
defer 
for i := 0; i < 10; i++ {
    _, err = stmt.Exec(i, "dummy")
    if err != nil {
        tx.Rollback()
        return nil,err
    }
}
err = tx.Commit()
if err != nil {
    stmt.Close()
    tx.Rollback()
    return nil,err
}
stmt.Close()
return someValue, nil

ref: https://stackoverflow.com/a/46476451/5466534