【问题标题】:Inserting an array into a Postgresql database将数组插入 Postgresql 数据库
【发布时间】:2014-12-29 17:08:48
【问题描述】:

我希望能够将一个 bigints 数组写入我在 Go 中用于历史记录的表中。不幸的是,我不能,当我这样做时,会抛出错误sql: converting Exec argument #1's type: unsupported type []int64, a slice。这是我正在做的,为简洁起见编辑:

type Card struct {
    cid int64
}

type Transaction struct {
        tid, cardid int64
        productids []int64
        salepoint int
        cardkey string
}

func logPurchase(card *Card, t *Transaction) {
     _, err := db.Exec("INSERT INTO history VALUES ($1, $2, $3, $4)", rand.Int63(), t.productids, card.cid, t.salepoint);
}

这是我希望插入的表的结构: tid bigint primary key, productids bigint[] not null, cardid bigint not null, salepoint int

【问题讨论】:

  • 您的值列表中似乎有一个额外的值。
  • 很好,不知道我是怎么把它放在那里的。我遇到此问题的源代码中不存在该问题。相应地更新了问题。
  • 数组类型是 postgresql 特有的。您可能需要使用为 postgresql 量身定制的库,例如:github.com/go-pg/pg
  • 在撰写本文时,lib/pq 库目前似乎没有处理数组类型,尽管有一个功能请求:github.com/lib/pq/issues/49
  • 建议在添加此功能后将接受的答案更新为stackoverflow.com/a/41337887/2662176

标签: postgresql go


【解决方案1】:

自 2016 年 8 月 6 日起,github.com/lib/pq 支持Arrays。 OP的声明可以写成:

_, err := db.Exec(
    "INSERT INTO history VALUES ($1, $2, $3, $4)", 
    rand.Int63(), 
    pq.Array(t.productids),   // <------- 
    card.cid, 
    t.salepoint,
)

【讨论】:

    【解决方案2】:

    使用自定义类型实现 database/sql/driver.Valuer:

    type int64array []int64
    
    func (a int64array) Value() (driver.Value, error) {
        // Format a in PostgreSQL's array input format {1,2,3} and return it as as string or []byte.
    }
    

    【讨论】:

    • 嗨,安迪,很酷的答案。你怎么能实现相反的呢?我需要实现的任何函数来执行 psql 数组 -> 切片?
    • 反向操作需要实现database/sql.Scanner接口。为此,您需要使用指针接收器。
    • 如果您愿意,可以将其添加到您的答案中以供参考 - 无论如何谢谢!
    • 已经在里面了,你可以用pg.Int64Array输入productids字段
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-12
    • 2019-06-19
    相关资源
    最近更新 更多