dongqiao8417
2017-10-21 03:16
浏览 168

对MySQL数据库进行动态SQL查询

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

This is far too much typing, especially if I have a dozen more variables I'd like to add to the WHERE condition.

If this were PHP, I'd do something like this:

$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);

By using a foreach loop, I can dynamically generate queries and dynamically bind as many variables as needed.

Is something like this an option with golang and mysql? Or are there alternatives to not typing out every single variable combination for a query?

1条回答 默认 最新

相关推荐 更多相似问题