Making dynamic SQL queries to a MySQL DB

后端 未结 1 452
星月不相逢
星月不相逢 2021-02-08 11:42

I\'ve never used golang with mysql before, so I\'m reading about these for the first time. I\'d like to do something like this:

if userId && gender &         


        
相关标签:
1条回答
  • 2021-02-08 12:24

    If you have a map with the field names and values like this:

    m := map[string]interface{}{"UserID": 1234, "Age": 18}
    

    then you can build the query like this:

    var values []interface{}
    var where []string
    for _, k := range []string{"userId", "gender", "age", "name", "height", "weight", "ethnicity"} {
        if v, ok := m[k]; ok {
            values = append(values, v)
            where = append(where, fmt.Sprintf("%s = ?", k))
        }
    }
    r, err := db.QueryRow("SELECT name FROM users WHERE " + strings.Join(where, " AND "), values...)
    

    This is not susceptible to SQL injection because placeholders are used for parts of the query outside the application's direct control.

    If the map keys are known to be allowed field names, then use this:

    var values []interface{}
    var where []string
    for k, v := range m {
        values = append(values, v)
        where = append(where, fmt.Sprintf("%s = ?", k))
    }
    r, err := db.QueryRow("SELECT name FROM users WHERE " + strings.Join(where, " AND "), values...)
    
    0 讨论(0)
提交回复
热议问题