【问题标题】:Go postgres `SELECT * IN` using array使用数组去 postgres `SELECT * IN`
【发布时间】:2018-11-08 23:08:58
【问题描述】:

我有一个简单的选择语句:

Select * FROM X where X.name in ("bob", "joe") and X.phone='123'

这在 postgres 中运行良好,

在我的 Go 代码中,我有以下代码:

var phone string = "123"
var names []string = []string{"bob", "joe"}
sqlStatement := `Select * FROM X where X.name in ($1) and X.phone=$2`
rows, sqlerr := db.Query(sqlStatement, names, phone)

但由于某种原因,我从那个 sql 中出错了。

不支持扫描,将 driver.Value 类型存储到 *string 类型中

如何在 sqlstatement 中使用我的名称数组?

注意:如果我执行 fmt.printf 并将 sql 语句粘贴到 postgres 中,我会返回数据 + 如果我取出 $1,并手动输入字符串

【问题讨论】:

标签: postgresql go


【解决方案1】:

从一些工作的 Go PostgreSQL 代码中复制和粘贴片段:

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

    query := `
            . . .
            WHERE code = ANY($1)
           . . .

        `

    codes := []string{"JFK", "LGA", "EWR"}
    rows, err := db.Query(query, pq.Array(codes))

【讨论】:

    【解决方案2】:

    我使用http://jmoiron.github.io/sqlx/#inQueries解决了这个问题

    var phone string = "123"
    var names []string = []string{"bob", "joe"}
    sqlStatement := `Select * FROM X where X.name in (?) and X.phone=?`
    sqlStatement, args, err := sqlx.In(sqlStatement, names, phone)
    sqlStatement = db.Rebind(sqlStatement)
            rows, sqlerr := db.Queryx(sqlStatement, args...)
    

    现在返回正确。

    解决此问题的另一种方法是使用fmt.Sprintf() 并将? 转换为%s

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-23
      • 1970-01-01
      • 1970-01-01
      • 2022-10-06
      • 2018-05-22
      • 2015-10-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多