doulongdan2264 2018-03-12 10:42
浏览 561

在golang中使用预处理语句时,是否总是需要延迟stmt.close()吗?

According to the post here, http://go-database-sql.org/modifying.html, there is no defer stmt.close(). However, there is a stmt.close() API in sql package. I can't seem to find information on whether it is necessary to defer closing the stmt when using prepared statement. Hence, the question - Do I always need to defer stmt.close() when I use prepared statement in golang?

  • 写回答

1条回答 默认 最新

  • dongmangzong8006 2018-03-12 11:42
    关注

    Using defer is not a requirement, it's a convenience and it offers safety. What matters is that if you create / prepare a statement (which uses some resources internally and may also use resources in the database server itself), then sometime, some point in the future you do call its Close() method in order to release resources allocated by it.

    Deferred functions are executed even if your function ends abruptly (e.g. you have an early return statement or even if your function panics), so using defer to close resources gives you safety that your code will not leak resources and / or memory.

    Note that defer will only run when the surrounding function returns. There may be cases when it is possible or even appropriate to close the statement earlier, and not wait until the surrounding function returns. A good example could be if you have a for loop doing many-many iterations, you would not want all the statements created in each iterations to keep resources until the for loop completes. In this case it is recommended to close resources before the next iteration begins. And in this case you would simply write a stmt.Close() instead of defer stmt.Close(), because the latter would not close the statement immediately, only when the function returns.

    Also note that "outsourcing" the loop's body to a separate function will also give you the possibility to use defer in that separate function, where the deferred close will happen before the next iteration begins. A variant of this may be that you use an anonymous function (a function literal) in the loop's body, where you also have the chance to use defer, e.g.:

    for _, v := range values {
        func() {
            stmt, err := db.Prepare("INSERT INTO users(name) VALUES(?)")
            if err != nil {
                // handle error
                return
            }
            defer stmt.Close()
    
            // Use stmt...
        }()
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)