将Postgresql数组直接读取到Golang Slice中 [英] Read a Postgresql array directly into a Golang Slice

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

问题描述

我有一个查询,该查询返回一行,其中一行包含字符串数组(字符不同[] ):

  {http://wp.me/p62MJv-Jc,http://tyrant.click/1LGBoD6} 


有没有简单的方法可以直接将其读入Golang切片中?例如,

  var arr [] string 

for rows.Next(){
行.Scan(&arr)
fmt.Println(len(arr))
}

产生:

  0 


解决方案

正如Victor在原始帖子这篇帖子以 pq.Array()的解释很好地回答了这个问题。



直接从链接中获取:


将Postgres数组值读取到Go切片中,使用:

  func getTags(db * sql.DB,标题字符串)(标签[] string){
//选择查询,返回1列数组类型
sel:=从帖子中的SELECT标签,其中title = $ 1

//将输出参数包装在pq.Array中以接收到
如果err:= db.QueryRow(sel,title).Scan(pq.Array(&a mp; tags)); err!= nil {
log.Fatal(err)
}

return
}


我也已经在自己的项目中使用了它,因此可以确认它是否有效。


I have a query which returns a row with a single column containing an array of strings (character varying[]):

{http://wp.me/p62MJv-Jc,http://tyrant.click/1LGBoD6}

Is there any easy way to read this directly into a Golang slice? E.g.

var arr []string

for rows.Next() {
    rows.Scan(&arr)
    fmt.Println(len(arr))
}

Produces:

0

解决方案

As mentioned by Victor in the comments on the original post, this post answers the question well with its explanation of pq.Array().

Taken directly from the link:

To read a Postgres array value into a Go slice, use:

func getTags(db *sql.DB, title string) (tags []string) {
    // the select query, returning 1 column of array type
    sel := "SELECT tags FROM posts WHERE title=$1"

    // wrap the output parameter in pq.Array for receiving into it
    if err := db.QueryRow(sel, title).Scan(pq.Array(&tags)); err != nil {
        log.Fatal(err)
    }

    return
}

I've just got this working in a project of my own as well, so can confirm it works.

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

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