我之前从未使用过golang和goql,所以我第一次阅读这些内容。我想做这样的事情:
if userId && gender && age
db.QueryRow("SELECT name FROM users WHERE userId=? AND gender=? AND age=?", userId,gender,age)
else if gender && age
db.QueryRow("SELECT name FROM users WHERE gender=? AND age=?", gender, age)
else if userId && gender
db.QueryRow("SELECT name FROM users WHERE userId=? AND gender=?", userId,gender)
else if userId && age
db.QueryRow("SELECT name FROM users WHERE userId=? AND age=?", userId, age)
else if gender
db.QueryRow("SELECT name FROM users WHERE gender=?", gender)
else if userId
db.QueryRow("SELECT name FROM users WHERE userId=?", userId)
else if age
db.QueryRow("SELECT name FROM users WHERE age=?", age)
打字太多了,特别是如果我还有十几个变量需要添加到WHERE条件中。
如果这是PHP,我会做这样的事情:
$sql = "SELECT name FROM users ";
$where = array();
foreach(explode(",","userId,gender,age,name,height,weight,ethnicity" as $field)
{
if(isset($arrayOfValues[$field]))
{
$where[count($where)] = $field." = ?".$field
$db->bind("?".$field,$arrayOfValues[$field]);
}
}
if(count($where)>0)
$sql = $sql . " WHERE ".implode(" AND ",$where);
$db->query($sql);
通过使用foreach循环,我可以动态生成查询并根据需要动态绑定任意数量的变量。
像golang和mysql这样的选项吗?或者是否有替代方法可以不为查询键入每个变量组合?
答案 0 :(得分:16)
如果您的地图名称和值如下所示:
m := map[string]interface{}{"UserID": 1234, "Age": 18}
然后您可以像这样构建查询:
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...)
这不容易受SQL注入影响,因为占位符用于应用程序直接控制之外的部分查询。
如果已知地图密钥是允许的字段名称,则使用:
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...)