dongzhuner6981 2017-09-25 18:26
浏览 78

sql.Query的参数数目可变

I'm trying to pass a variable number of arguments to db.Query() in Go. I'm doing something like:

var values []interface{}
query := []string{"SELECT * FROM table"}
sep := "WHERE"

if ... {
    values = append(values, something)
    query = append(query, fmt.Sprintf(` %s field_a=$%d`, sep, len(values))
    sep = "AND"
}

if ... {
    values = append(values, something)
    query = append(query, fmt.Sprintf(` %s field_b=$%d`, sep, len(values))
    sep = "AND"
}

// Add an arbitrary number of conditional arguments...

rows, err := db.Query(strings.Join(query, " "), values...)

The query looks fine, and the values are all there, but I'm not getting anything back from the query. Some of the values are integers, some strings. When I manually try the exact same query (copy/paste) in psql, I substituting the actual values for $1, $2, etc, I get correct results. What am I missing?

Edit

Here's an example of what the final query (the result of strings.Join()) should look like:

SELECT
    table1.field1, table1.field2, table1.field3,
    table2.field4, table2.field6, table2.field6
FROM table1, table2
WHERE
    table1.field2=$1 AND
    table2.field3 IN ($2, $3)

When I try:

SELECT
    table1.field1, table1.field2, table1.field3,
    table2.field4, table2.field6, table2.field6
FROM table1, table2
WHERE
    table1.field2='something' AND
    table2.field3 IN (40, 50)

from psql, it works fine. When I call:

var values []interface{}
values = append(values, "something")
values = append(values, 40)
values = append(values, 50)
db.Query(`SELECT
    table1.field1, table1.field2, table1.field3,
    table2.field4, table2.field6, table2.field6
FROM table1, table2
WHERE
    table1.field2=$1 AND
    table2.field3 IN ($2, $3)`, values...)

from Go, I get a Rows object that returns false the first time rows.Next() is called, and a nil error.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
    • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
    • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
    • ¥15 如何在炒股软件中,爬到我想看的日k线
    • ¥15 seatunnel 怎么配置Elasticsearch
    • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
    • ¥15 (标签-MATLAB|关键词-多址)
    • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
    • ¥500 52810做蓝牙接受端
    • ¥15 基于PLC的三轴机械手程序