我希望能够将一个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);
}
Run Code Online (Sandbox Code Playgroud)
这是我希望插入的表的结构:
tid bigint primary key, productids bigint[] not null, cardid bigint not null, salepoint int
ken*_*ytm 18
github.com/lib/pq自2016年8月6日起支持数组.OP的声明可以写成:
_, err := db.Exec(
"INSERT INTO history VALUES ($1, $2, $3, $4)",
rand.Int63(),
pq.Array(t.productids), // <-------
card.cid,
t.salepoint,
)
Run Code Online (Sandbox Code Playgroud)
使用自定义类型实现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.
}
Run Code Online (Sandbox Code Playgroud)