On Mon, Jul 22, 2019 at 9:35 AM Tong Sun <suntong...@gmail.com> wrote: > > All SQL DB statements need a sql.DB connection: > > var conn *sql.DB = ... > defer conn.Close() > > statement, err := conn.Prepare(SQL) > > > My question is, if I want to reuse the `conn` variable later on in the same > function, > > conn, err = sql.Open("mssql", NewConnString)
If you didn't close conn here, then it will leak. The defer will close the second connection, not the first. You can add a second defer after opening the second connection. Or, use a different variable and defer closing of that as well. Closing the first connection manually before opening the second won't work. The first defer will try to close the first connection. Defer evaluates its arguments when it is declared, not when it runs. > > > Do I need to put another `defer conn.Close()` after it, or the first `defer > conn.Close()` still applies? Or I should call `conn.Close()` explicitly > beforehand? > > thanks > > -- > You received this message because you are subscribed to the Google Groups > "golang-nuts" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to golang-nuts+unsubscr...@googlegroups.com. > To view this discussion on the web visit > https://groups.google.com/d/msgid/golang-nuts/11c35ccc-0713-4e09-8325-a4e608758b15%40googlegroups.com. -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/CAMV2RqrkNLeBmWuFS6yE-L_VDRDZaOCrmJASP0n3g22p4rnNTg%40mail.gmail.com.