在Golang中将数组插入到Postgresql数据库中 [英] Inserting an array into a Postgresql database in Golang

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

问题描述

我希望能够将一个bigint数组写入我在Go中用于历史记录的表中。不幸的是,我不能,当我做错误 sql:转换Exec参数#1的类型:不支持的类型[] int64时,会引发片段。这是我正在做的,为简洁起见编辑:

 类型卡结构{
cid int64
}

类型事务结构{
tid,cardid int64
productids [] int64
salepoint int
cardkey字符串
}

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不为空,salepoint int

解决方案

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

 类型int64array [] int64 

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


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

解决方案

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

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

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