This question already has answers here:
PDO binding values for MySQL IN statement [duplicate]

(8个答案)


6年前关闭。




在编写Web应用程序时,我们将使用SQL prepare而不是concat SQL字符串来避免SQL注入。例如:
sql.exec("select * from user where user_id=?", user_id)

但是如何在SQL中编写prepare WHERE...IN?例如:
sql.exec("select * from user where user_id in ?", user_ids)

如果不可能的话。在这种情况下,避免SQL注入的正确方法是什么?

谢谢。

最佳答案

将user_ids字符串更改为id数组:

idArr = strings.Split(user_ids, ",")

创建SQL:
vals := []interface{}{}
sqlStr := "select * from user where user_id in ("
for _,v := range idArr {
    vals = append(vals, v)
    sqlStr += "?,"
}
sqlStr = strings.TrimRight(sqlStr, ",")
sqlStr += ")"

stmt, err := db.Prepare(sqlStr)
if err!=nil{
    return err
}
defer stmt.Close()

rows, err := stmt.Query(vals...)

09-26 14:47