Should we also close DB's .Prepare() in Golang?

十年热恋 提交于 2019-12-22 10:45:52

问题


From this tutorial shown that rows.Closed() must be called where rows is from stmt.Query(), is stmt.Closed() also should be called where stmt is from db.Prepare()?

// inside a function
stmt, err := db.Prepare(cmd) // cmd is SQL string
Check(err)
// should we add: defer stmt.Close()
rows, err := stmt.Query(params) // params is map/interface{}
defer rows.Close()
Check(err)

回答1:


The short answer is Yes. You should call stmt.Close();

The long answer can be found in this google groups thread.




回答2:


Use as follows

// inside a function
stmt, err := db.Prepare(cmd) // cmd is SQL string
if err != nil {
    println(err.Error())
}
defer stmt.Close()
rows, err := stmt.Query(params) // params is map/interface{}

if err != nil {
    println(err.Error())
}


来源:https://stackoverflow.com/questions/27287894/should-we-also-close-dbs-prepare-in-golang

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!