我有以下代码:
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)
}
}
我将pq.Array作为参数传递给Golang Postgres格式字符串$ 1。但是参数无法通过。当我希望输出B,C
时,程序正在打印A,B,C
。
# Querying with blacklist in SQL
B
C
Querying with blacklist in Golang
A
B
C