在使用“数据库/ SQL”时如何防止Go中的SQL注入攻击?

问题描述:

Building my first web-app and want to understand SQL injection better (https://github.com/astaxie/build-web-application-with-golang/blob/master/en/eBook/09.4.md).

How much protection against SQL injection do I get from just always using the 'database/sql' library and constructing queries using '?' instead of concatting strings? What kind of SQL injection attacks will I still have to worry about in that case?

构建我的第一个网络应用,并希望更好地理解SQL注入( https://github.com/astaxie/build-web-application-with -golang / blob / master / en / eBook / 09.4.md )。 p>

仅通过始终使用“数据库/ sql”,我可以获得多少防止SQL注入的保护 库并使用“?”构造查询 而不是容纳字符串? 在这种情况下,我仍然需要担心哪种SQL注入攻击? p> div>

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