douyin7829 2017-04-14 07:57
浏览 71
已采纳

IN pq.Array无法传递值

I have the following code:

package main

import (
    "database/sql"
    "fmt"
    "github.com/lib/pq"
)

const (
    DB_USER     = "<username>"
    DB_PASSWORD = "<password>"
    DB_NAME     = "<db>"
)

func main() {
    dbinfo := fmt.Sprintf("user=%s password=%s dbname=%s sslmode=disable",
    DB_USER, DB_PASSWORD, DB_NAME)

    db, err := sql.Open("postgres", dbinfo)
    checkErr(err)
    defer db.Close()

    fmt.Println("# Querying with blacklist in SQL")
    rows, err := db.Query(`
    SELECT * FROM(
        SELECT x from (values ('A'), ('B'), ('C') ) s(x)
    ) As Res1 WHERE x NOT IN ('A');
`)
    checkErr(err)

    for rows.Next() {
        var str string
        err = rows.Scan(&str)
        fmt.Println(str) // Prints B,C
    }

    fmt.Println("Querying with blacklist in Golang")
    blacklist := []string{"A"}

    q := `
    SELECT * FROM(
        SELECT x from (values ('A'), ('B'), ('C') ) s(x)
    ) As Res1 WHERE x NOT IN ($1);

`
    rows, err = db.Query(q, pq.Array(blacklist))
    checkErr(err)

    for rows.Next() {
        var str string
        err = rows.Scan(&str)
        fmt.Println(str) // Prints A, B, C
    }
}

func checkErr(err error) {
    if err != nil {
        panic(err)
    }
}

where I pass a pq.Array as a parameter to a Golang Postgres format string $1. However the parameter fails to get passed. When I expect an output of B,C, the program is printing A,B,C.

# Querying with blacklist in SQL
B
C
Querying with blacklist in Golang
A
B
C
  • 写回答

1条回答 默认 最新

  • duanhuo0577 2017-04-14 09:00
    关注

    Postgres's IN does not take an array like for example ANY or ALL which is where you can use pq.Array.

    Instead of using x NOT IN($1) you can use x <> ALL($1).

    From ALL's docs.

    The left-hand expression is evaluated and compared to each element of the array using the given operator, which must yield a Boolean result. The result of ALL is "true" if all comparisons yield true (including the case where the array has zero elements). The result is "false" if any false result is found.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥15 pyqt信号槽连接写法
  • ¥500 把面具戴到人脸上,请大家贡献智慧,别用大模型回答,大模型的答案没啥用
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。