簡體   English   中英

在golang中使用postgres IN子句

[英]Using postgres IN clause in golang

我一直在嘗試在golang中使用postgres IN子句,但始終會出錯。 這是我要執行的查詢。

SELECT id1 FROM my_table WHERE type = (an int) AND id2 = (an int) AND id1 IN (list of UUIDs)

我使用此代碼構造了此查詢,但出現以下錯誤。

var params []interface{}
inCondition := ""
params = append(params, type)
params = append(params, id2)
for _, id := range id1 {
    params = append(params, id)
    if inCondition != "" {
        inCondition += ", "
    }
    inCondition += "?"
}
query := fmt.Sprintf(`SELECT id1 FROM my_table WHERE type = ? AND id2 = ? AND id1 IN (%s)`, inCondition)
rows, err := db.Query(query, params...)

我得到的查詢:

SELECT id1 FROM my_table WHERE type = ? AND id2 = ? AND id1 IN (?, ?, ?)

參數輸出:

[]interface {}=[0 7545449 d323f8d5-ab97-46a3-a34e-95ceac2f3a6a d323f8d5-ab97-46a3-a34e-95ceac2f3a6b d323f8d5-ab97-46a3-a34e-95ceac2f3a6d]

錯誤:

pq: syntax error at or near \"AND\""

我想念什么? 或者,我將如何使其工作? id1是長度可變的UUID的一部分。

代替?,使用$ 1,$ 2等作為占位符起作用。

遇到類似的問題。 記不清我到底是在哪里撿到的,但是我記得在處理整數和字符串類型的數組時仍然遇到問題。 我要做的是擁有一個本地自定義類型,並為其返回驅動程序兼容的值。 請參閱下面的示例。

// Int64Array is a type implementing the sql/driver/value interface
// This is due to the native driver not supporting arrays...
type Int64Array []int64

// Value returns the driver compatible value
func (a Int64Array) Value() (driver.Value, error) {
    var strs []string
    for _, i := range a {
        strs = append(strs, strconv.FormatInt(i, 10))
    }
    return "{" + strings.Join(strs, ",") + "}", nil
}

強烈建議簽出sqlx 編寫了一個名為papergres的簡單orm包裝器,使我的+ postgres生活更加輕松:)試試看。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM