doubaoxue5788 2017-07-03 07:01
浏览 161

在Golang中重用或复制* sql.Rows

Is it possible to reuse the same *sql.Rows after the *sql.Rows.Next() was called so I could pass it to another function?

rows, err := db.Query(...)
for rows.Next() {
    // rows.Scan()
}
anotherFunction(rows) // NOT WORKING: This rows became empty.

I tried to make another copy of the *sql.Rows but it didn't work.

rows, err := db.Query(...)
anotherRows := *rows
// PANIC: call of load copies lock value: database/sql.Rows contains sync.RWMutex
  • 写回答

1条回答 默认 最新

  • dongshuiga2826 2017-07-03 14:33
    关注

    The database/sql package does not provide any means to rewind the Rows, after you have read them, i.e. it is a "forward only" result set.

    Moreover, it will maintain a link to the underlying (physical) database connection, inside it, making it a bad idea to copy it or pass it around.

    If you need to apply multiple functions to your data, just Scan all the rows, to get a slice of data objects, and then pass this around.

    Scan will make a copy of the data you read:

    Scan copies the columns from the matched row into the values pointed at by dest.

    so you can then safely Close your Rows object (releasing any associated database resources).

    You should watch out for errors too, after executing the Query (err) and after reading the rows, via rows.Err().

    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测