I'm using the MySQL driver for Golang provided here
https://github.com/go-sql-driver/mysql
One of the things I'm trying to do is store the database variable in a global connection. According to the documentation, sql.Open() is supposed to return a pointer to a DB struct, so I tried storing it as
var db *DB
However, that resulted in the error
undefined: DB
The next thing I tried was to look at the source code for the MySQL driver, and I found a snippet of code here https://github.com/go-sql-driver/mysql/blob/master/driver.go
func (d MySQLDriver) Open(dsn string) (driver.Conn, error) {
So, I tried to save the variable as driver.Conn - however, I was unable to (incorrect imports). I wasn't able to import driver either.
The last thing I tried was to use reflect to bring the name of the variable to light
package main
import (
"fmt"
"reflect"
)
import "database/sql"
import _ "github.com/go-sql-driver/mysql"
func main() {
db, _ := sql.Open("mysql", "root:password@/Tracker")
yt := reflect.TypeOf(db).Kind()
fmt.Printf("%T: %s\n", yt, yt)
}
Unfortunately, that didn't work either - it shows up as pointer, and not the type of variable it's actually pointing to.
I'm at a loss as to how to figure it out now. Thanks in advance for your help!
Approach 1: Use Global Variable Declare a global variable DB of type *sql. DB to hold the database connection. Write a function that will open the connection and assign it to the global variable. Now, where ever you need to access the database, you can simply import the global variable and start using it.
php //Connect To Database function connect_to_database() { require_once 'config. php'; global $db_host; global $db_database; global $db_user; global $db_pass; $db_server = mysqli_connect($db_host, $db_user, $db_pass); if (!$
You need to qualify the name of the type with the package name:
import(
"database/sql"
"github.com/go-sql-driver/mysql"
)
var db *sql.DB // Note the sql package provides the namespace
func main() {
var err error
// Make sure not to shadow your global - just assign with = - don't initialise a new variable and assign with :=
db, err = sql.Open(...)
if err != nil {
// Handle the error!
}
}
Whether you want to have a global (easy to get started) or pass it around explicitly is up to you, but I'd suggest just keeping it simple for now. If this is going into a web application, you can safely share the *sql.DB
connection pool across handlers/requests.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With