将数组插入Postgresql数据库 [英] Inserting an array into a Postgresql database

查看:93
本文介绍了将数组插入Postgresql数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够将bigints数组写入要用于Go历史记录的表中。不幸的是,当我出现错误 sql:转换Exec参数#1的类型:不受支持的类型[] int64时,会引发切片。为简化起见,以下是我正在做的事情:

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

这是我要插入的表的结构:
tid bigint主键,productids bigint []不为空,cardid bigint不为空,salespoint int

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

推荐答案

使用自定义类型实现数据库/sql/driver.Valuer:

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

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.
}

这篇关于将数组插入Postgresql数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆