duandao7704 2014-11-03 03:55
浏览 881
已采纳

在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

  • 写回答

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,
    )
    
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 报错问题,只有两个错误,如图片所示,i多次初始化
  • ¥15 matlab runtime 如何收费
  • ¥20 用C语言绘制cs1.6方框透视 出现了点问题 绘制不上去 矩阵数据 和敌人坐标都是正确的
  • ¥15 Tpad api账户 api口令
  • ¥30 ppt进度条制作,vba语言
  • ¥15 生信simpleaffy包下载
  • ¥15 请教一下simulink中S函数相关问题
  • ¥15 在二层网络中,掩码存在包含关系即可通信
  • ¥15 端口转发器解析失败不知道电脑设置了啥
  • ¥15 Latex算法流程图行号自定义