golang 连接、操作完mysql, 对mysql的连接会自动关闭,还是必须要手动关闭?
怪我咯
怪我咯 2017-04-17 11:03:43
0
4
618

参考 astaxie 的代码

import (
    _ "code.google.com/p/go-mysql-driver/mysql"
    "database/sql"
    "fmt"
    //"time"
)

func main() {
    db, err := sql.Open("mysql", "astaxie:astaxie@/test?charset=utf8")
    checkErr(err)

    //插入数据
    stmt, err := db.Prepare("INSERT userinfo SET username=?,departname=?,created=?")
    checkErr(err)

    res, err := stmt.Exec("astaxie", "研发部门", "2012-12-09")
    checkErr(err)

    id, err := res.LastInsertId()
    checkErr(err)

    fmt.Println(id)

    //删除数据
    stmt, err = db.Prepare("delete from userinfo where uid=?")
    checkErr(err)

    res, err = stmt.Exec(id)
    checkErr(err)

    affect, err = res.RowsAffected()
    checkErr(err)

    fmt.Println(affect)

}

func checkErr(err error) {
    if err != nil {
        panic(err)
    }
}

求教:这段代码对数据库的连接没有主动关闭(调用 db.Close()), 是不是Go的垃圾收集自动关闭释放资源呢? 还是必须手动调用db.Close()释放资源?

怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(4)
刘奇

The database link must be closed manually. This is the same as opening a file

左手右手慢动作

Go garbage collection is memory garbage collection, the memory allocated to objects is recycled. Resources must be released manually and returned to the operating system

Peter_Zhu

If you don’t close it manually, golang will automatically close it for you when your program ends or when the connection object goes out of scope. . . However, manual shutdown is still supported. . . This is good practice. . .

小葫芦

Of course you don’t need to close it, mysql will be closed automatically after a while. But you need to get into the habit of turning it off manually.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template