duandao7704
2014-11-03 03:55
浏览 582

在Golang中将数组插入Postgresql数据库

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

图片转代码服务由CSDN问答提供 功能建议

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

  type Card struct {
 cid int64 
} 
 
type Transaction struct {
 tid,cardid int64 \  n productids [] int64 
 salepoint int 
 cardkey string 
} 
 
func logPurchase(card * Card,t * Transaction){
 _,err:= db.Exec(“插入历史记录值($ 1,  $ 2,$ 3,$ 4)”,rand.Int63(),t.productids,card.cid,t.salepoint); 
} 
   
 
 

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

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douyanning3724 2014-11-03 17:19
    已采纳

    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.
    }
    
    打赏 评论
  • du512053619 2016-12-27 01:21

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

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

相关推荐 更多相似问题