Gambit2007
Gambit2007

Reputation: 4006

Can't connect to a DB: database is closed

I have the following project structure:

-main.go
-db
--dbinit.go

In dbinit.go i have the following code:

package db

import (
    "database/sql"
    _ "github.com/go-sql-driver/mysql"
)

var Db *sql.DB
var err error

func init() {
    Db, err = sql.Open("mysql", "myDBCreds")
    defer Db.Close()
}

and in main.go i have:

package main 

import (
    db "./db"
)

func main() {

    defer db.Db.Close()

        sqlStatement := `INSERT INTO table (field1, field2)
            VALUES ($1, $2)
        `
        _, err := db.Db.Exec(sqlStatement, param1, param2)
        if err != nil {
            panic(err)
        }

but main.go keeps throwing an error:

sql: database is closed

What am i doing wrong?

Upvotes: 1

Views: 3205

Answers (1)

mewi
mewi

Reputation: 352

From a previously asked question

The returned DB is safe for concurrent use by multiple goroutines and maintains its own pool of idle connections. Thus, the Open function should be called just once. It is rarely necessary to close a DB.

Aka, don't close it.

Upvotes: 2

Related Questions