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 &
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...)