将数组插入到PostgreSQL数据库中

huangapple go评论86阅读模式
英文:

Inserting an array into a Postgresql database

问题

我想要能够将一个bigint数组写入我在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

英文:

I want to be able to write an array of bigints into a table that I am using for history in Go. Unfortunately, I can't and when I do the error sql: converting Exec argument #1's type: unsupported type []int64, a slice is thrown. Here's what I'm doing, edited for brevity:

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);
}

This is the structure of the table that I wish to insert into:
tid bigint primary key, productids bigint[] not null, cardid bigint not null, salepoint int

答案1

得分: 30

Arrays 自 2016 年 8 月 6 日起在 github.com/lib/pq 中得到支持。 OP 的语句可以写成:

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

Arrays are supported in github.com/lib/pq since 2016 Aug 6th. OP's statement could be written as:

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

答案2

得分: 12

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

type int64array []int64

func (a int64array) Value() (driver.Value, error) {
    // 将 a 格式化为 PostgreSQL 的数组输入格式 {1,2,3},并将其作为字符串或 []byte 返回。
}

请注意,这只是一个示例代码,你需要根据实际需求来实现 Value() 方法。

英文:

Implement database/sql/driver.Valuer with a custom type:

type int64array []int64

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

huangapple
  • 本文由 发表于 2014年11月3日 11:55:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/26707553.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定