0

I am trying to insert something into a MySQL database with this code. When I run a debugger I see that it stops at this line:

stmt, err := users_db.Client.Prepare(queryInsertUser)

and my debugger takes me to this line and the value of db is nil. Note that these lines are not mine and is supposed to be the internal Go modules etc. Also my database connection has been made as I can see in my console.

// conn returns a newly-opened or cached *driverConn.
func (db *DB) conn(ctx context.Context, strategy connReuseStrategy) (*driverConn, error) {
    db.mu.Lock()
    if db.closed {
        db.mu.Unlock()
        return nil, errDBClosed
    }

and

func (user *User) Save() *errors.RestError {
    stmt, err := users_db.Client.Prepare(queryInsertUser)
    if err != nil {
        return errors.NewInternalServerError(err.Error())
    }
    defer stmt.Close()
    insertResult, err := stmt.Exec(user.FirstName, user.LastName, user.Email, user.DateCreated)
    // not so important part removed 
    return nil
}

and code inside my users_db package

package users_db

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

var (
    Client   *sql.DB
    username = "bla bla"
    password = "bla bla"
    host     = "bla bla"
    schema   = "bla bla"
)

func init() {
    dataSourceName := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8",
        username, password, host, schema,
    )
    var err error
    Client, err := sql.Open("mysql", dataSourceName)
    if err != nil {
        panic(err)
    }
    if err = Client.Ping(); err != nil {
        panic(err)
    }

    log.Println("database successfully configured")
}

What can be the reason for this error and how can this be resolved?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
horrible_nerd
  • 115
  • 3
  • 9
  • `:=` re-declares `Client` in the scope of `init`, leaving the `Client` at the package level unchanged. Instead use `=`. https://golang.org/ref/spec#Short_variable_declarations – mkopriva Mar 28 '20 at 15:24

1 Answers1

0

As @mkopriva commented you are declaring Client again in init. You can resolve it by doing this:

c, err := sql.Open("mysql", dataSourceName) 
Client = c
gipsy
  • 3,859
  • 1
  • 13
  • 21