|
我以前从未做过golang与mysql所以我是- v2 r* ~! U+ Z1 N
第一次阅读这些内容。我想做这样的事:
5 j s$ Z% `5 m4 O' f, gif userId && gender && agedb.QueryRow("SELECT name FROM users WHERE userId=? AND gender=? AND age=?",userId,gender,age)else if gender && agedb.QueryRow("SELECT name FROM users WHERE gender=? AND age=?",gender,age)else if userId && genderdb.QueryRow("SELECT name FROM users WHERE userId=? AND gender=?",userId,gender)else if userId && agedb.QueryRow("SELECT name FROM users WHERE userId=? AND age=?",userId,age)else if genderdb.QueryRow("SELECT name FROM users WHERE gender=?",gender)else if userIddb.QueryRow("SELECT name FROM users WHERE userId=?",userId)else if agedb.QueryRow("SELECT name FROM users WHERE age=?",age)这种输入太多了,尤其是当我想到的时候
- u7 g4 D5 k5 y添加更多变量WHERE条件中时。
6 ~0 A7 k( r2 R- m+ z+ j3 G如果这是PHP,我将执行以下操作:
; T B$ e0 f6 D( J4 d5 f$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循环,我可以动态生成查询,并根据需要动态绑定尽可能多的变量。8 X# R5 B( _* ~& }8 ^
像golang和mysql这样的选项吗?还是还有其他选择输入每个变量组合?& ?; M3 C9 Y4 s h- g8 l
+ D6 t; M/ x* |( c1 r
解决方案: 6 Q; \# w7 f4 b4 \ L
假如你的地图有这样的字段名称和值:/ I4 c ?# w8 h; v% M" }( Y+ U
m := map[string]interface{}{"UserID": 1234,"Age": 18}那么您可以像这样构建查询: T$ ~, G, T0 T+ ^0 p0 \
var values []interface{}var where []stringfor _,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由于占位符用于注入的影响 D8 X3 m. ~8 Y. y1 B
在应用程序直接控制范围之外的查询部分。. Q/ W* U* S0 A4 ^+ K
若已知映射键允许使用字段名称,请使用以下命令:
% \/ u. Q# g8 u0 o. ]3 jvar values []interface{}var where []stringfor 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...) |
|