Better/shorter Go 中关闭数据库连接的方法

Better/shorter way to close database connection in Go

一般我都是这样写的

rows := db.MyPgConn.QueryRows(`SELECT * FROM bla`) // or any other query
for rows.Next() { // if there are result
   // rows.Scan( 
   // do custom operation
}
rows.Close() // close recordset

但是那样的话,有可能我忘记写rows.Close()就像这样code可能会使可用connection/socket的数量耗尽,有没有更好的方法这个?

正如 Intermernet 所提到的,defer 语句是使 close 语句更接近声明 rows var 的位置的最佳方式。我能想到的唯一可能使这个更短或更容易的方法是围绕您的数据库调用创建一个包装函数。

func performQuery(q string, op func(db.rows)) {
    rows := db.MyPg.Conn.QueryRows(q)
    // defer rows.Close()
    op(rows)
    rows.Close()
}

// then we could do:
performQuery(`SELECT * FROM bla`,func(rows db.Rows) {
  for rows.Next() {
    // rows.Scan(      
  }
})

然而,这会限制您使用参数进行查询(例如 SELECT * FROM tableName WHERE id =

Go 介绍 defer 正是为此目的。

rows := db.MyPgConn.QueryRows(`SELECT * FROM bla`) // or any other query
defer rows.Close()

for rows.Next() { // if there are result
   // rows.Scan( 
   // do custom operation
}

来自文档:

Deferring a call to a function such as Close has two advantages. First, it guarantees that you will never forget to close the file, a mistake that's easy to make if you later edit the function to add a new return path. Second, it means that the close sits near the open, which is much clearer than placing it at the end of the function.