dongqiang5932 2017-09-17 17:47
浏览 23
已采纳

从存储过程检索结果的惯用方式是什么?

DROP function mytest();
CREATE OR REPLACE FUNCTION mytest() 
RETURNS TABLE(name text, age int)
 AS 
$$ 
SELECT name, age FROM names
$$ 
LANGUAGE sql;

Most of the examples I've seen with a stored procedure return a single row with a single column and can be used with QueryRow. Here I am using a table as the output. This above returns 4 rows:

    mytest   
------------
 (bob,12)
 (fred,18)
 (james,22)
 (bill,27)
(4 rows)

In Go, what is the idiomatic way to deal with the tuples:

rows, err := db.Query("SELECT mytest()")
if err != nil {
    panic(err)
}

defer rows.Close()
for rows.Next() {
    var items string

    if err = rows.Scan(&items); err != nil {
        panic(err)
    }

    log.Println(items) // items is a string...now what?

}
if err = rows.Err(); err != nil {
    panic(err)
}

// prints some tuples:

(bob,12)
(fred,18)
(james,22)
(bill,27)

Maybe there's a package for this but I haven't found it ;(

  • 写回答

1条回答 默认 最新

  • douchui3933 2017-09-17 17:55
    关注

    Instead of a Query, you could try a PostgreSQL typesafe1 ORM , like src-d/go-kallax, which deals with tuples.

    You can see kalax presented in this blog post

    • the first priority of kallax is to provide type safety to the data access layer.
    • Another goal of kallax is to make sure all models are, first and foremost, Go structs without having to use database-specific types such as, for example, sql.NullInt64. Support for arrays and slices of all basic Go types and all JSON and arrays operators is provided as well.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒