gpt4 book ai didi

postgresql - 未应用过滤器(即空的“Where”子句)时,使用Golang网络表单从Postgres获取所有记录

转载 作者:行者123 更新时间:2023-12-01 22:23:45 29 4
gpt4 key购买 nike

我有一个Golang函数从Postgres数据库中获取所有记录,该函数只是使用:
SELECT * from stock_transactions我想对此功能应用过滤器以在某些条件下获取记录,简而言之,我想使用:
SELECT * from stock_transactions WHERE symbol = $symb
问题在于处理以下情况:如果$symb = null,查询应充当SELECT * from stock_transactions。我可以为它写一个if-else子句,但是如果参数数量大于2,可能会很混乱。有没有更好的方法来解决这个问题?

我的功能:

func showstocks (w http.ResponseWriter, r *http.Request){

var err error

if r.Method != "GET" {
http.Error(w, http.StatusText(405), http.StatusMethodNotAllowed)
return
}

rows, err := db.Query("SELECT * FROM stock_transaction ORDER BY id DESC")
if err != nil {
http.Error(w, http.StatusText(500), 500)
return
}
defer rows.Close()

sks := make([]stockdata, 0)


for rows.Next() {
sk := stockdata{}
err := rows.Scan(&sk.Sname, &sk.Ttype, &sk.Uprice, &sk.Qty, &sk.Bfee, &sk.Ddate)
if err != nil {
http.Error(w, http.StatusText(500), 500)
return
}
sks = append(sks, sk)
}
if err = rows.Err(); err != nil {
http.Error(w, http.StatusText(500), 500)
return
}

tpl.ExecuteTemplate(w, "dashboard.gohtml", sks)

}

最佳答案

//由@mkopriva建议。尝试和测试。

包主

导入(
“fmt”
)

func main(){
// ...

// use interface{} because string types cannot be nil
var stock_symbol interface{} // the "zero-value of interface types is nil, so stock_symbol here is nil

// if empty then stock_symbol will be left as nil
if val := r.FormValue("stock_symbol"); len(val) > 0 {
stock_symbol = val // set to the provided value
}

// ...

// now stock_symbol is either the provided string value or nil
db.Query("SELECT ... WHERE (stock_symbol = $1 OR $1 IS NULL)", stock_symbol)

}

关于postgresql - 未应用过滤器(即空的“Where”子句)时,使用Golang网络表单从Postgres获取所有记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61271894/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com