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.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?