参考 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()释放资源?
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
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.