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?