如何根据我拥有/获取的参数构建动态UPDATE查询?
仅当参数值不为空时才需要更新列。
这是我的代码:
func main() {
err := DBConnect() //DB connection function
if err != nil {
fmt.Println("Error", "DB Connect fail")
return
}
tx, err := Db.Begin()
if err != nil {
fmt.Println("Error", err)
fmt.Println("Error", "Unable to start DB")
return
}
defer func() {
if err != nil {
tx.Rollback()
} else {
tx.Commit()
}
}()
var arg []interface{}
i := 1
col1 := "value1"
col2 := "value2"
col3 := ""
col4 := ""
col5 := "value5"
query := "UPDATE schema1.products SET "
if col1 != "" {
query = query + "col1=$" + fmt.Sprintf("%d", i) + ", "
arg = append(arg, col1)
i++
}
if col2 != "" {
query = query + "col2=$" + fmt.Sprintf("%d", i) + ", "
arg = append(arg, col2)
i++
}
if col3 != "" {
query = query + "col3=$" + fmt.Sprintf("%d", i) + ", "
arg = append(arg, col3)
i++
}
if col4 != "" {
query = query + "col4=$" + fmt.Sprintf("%d", i) + ", "
arg = append(arg, col4)
i++
}
query = query + "WHERE col5=$" + fmt.Sprintf("%d", i)
arg = append(arg, col5)
stmt, err := tx.Prepare(query)
if err != nil {
fmt.Println("Error", err)
fmt.Println("Error", "Query prepare failed")
return
}
res, err := stmt.Exec(arg...)
if err != nil {
fmt.Println("Error", err)
fmt.Println("Error", "Query Exec failed")
return
}
n, err := res.RowsAffected()
if err != nil {
fmt.Println("Error", err)
fmt.Println("Error", "Unable to get rows affected")
return
}
if n > 1 {
fmt.Println("Error", err)
fmt.Println("Error", "More than one row updated")
return
}
return
}
因此,基本要求是仅在相应的Input值不为空时才更新列。
更新
func GetRow(arg1, arg2 string) (data [][]string, err error) {
row, err := Db.Query("SELECT * FROM schema1.products WHERE ($1='' OR col1=$1) AND ($2='' OR col2=$2)", arg1, arg2)
if err != nil {
fmt.Println("Error", err)
fmt.Println("Error", "Unable to Query DB")
return
}
defer sql.Close(row)
_, data, err = sql.Scan(row)
if err != nil {
fmt.Println("Error", err)
fmt.Println("Error", "Unable to scan rows")
return
}
if len(data) < 0 {
fmt.Println("Error", "No Data found")
return
}
return
}
GetRow函数中的查询仅在参数不为空时才包含WHERE子句中的条件。所以我不用担心arg1和arg2是否为空。我正在寻找一种方法来做同样的UPDATE查询。