One popular approach is to store the secrets in the environment before the program starts, perhaps loaded from a secret manager, and then your Go program can read them using os.Getenv:

username := os.Getenv("DB_USER")
password := os.Getenv("DB_PASS")
Adapting the preceding sql.Open example to use sql.OpenDB, you could create a handle with code such as the following:

// Specify connection properties.
cfg := mysql.Config{
    User:   username,
    Passwd: password,
    Net:    "tcp",
    Addr:   "127.0.0.1:3306",
    DBName: "jazzrecords",
}

// Get a driver-specific connector.
connector, err := mysql.NewConnector(&cfg)
if err != nil {
    log.Fatal(err)
}

// Get a database handle.
db = sql.OpenDB(connector)
For example, you could replace the preceding example with the following, which uses the MySQL driver’s Config to specify properties and its FormatDSN method to build a connection string.

// Specify connection properties.
cfg := mysql.Config{
    User:   username,
    Passwd: password,
    Net:    "tcp",
    Addr:   "127.0.0.1:3306",
    DBName: "jazzrecords",
}

// Get a database handle.
db, err = sql.Open("mysql", cfg.FormatDSN())
if err != nil {
    log.Fatal(err)
}
To make the driver available to your code, you import it as you would another Go package. Here’s an example:

import "github.com/go-sql-driver/mysql"
Code in the following example pings the database to confirm a connection.

db, err = sql.Open("mysql", connString)

// Confirm a successful connection.
if err := db.Ping(); err != nil {
    log.Fatal(err)
}
Note that if you’re not calling any functions directly from the driver package –- such as when it’s being used implicitly by the sql package – you’ll need to use a blank import, which prefixes the import path with an underscore:

import _ "github.com/go-sql-driver/mysql"
One popular approach is to store the secrets in the environment before the program starts, perhaps loaded from a secret manager, and then your Go program can read them using os.Getenv:

username := os.Getenv("DB_USER")
password := os.Getenv("DB_PASS")
Here’s an example for MySQL:

db, err = sql.Open("mysql", "username:password@tcp(127.0.0.1:3306)/jazzrecords")
if err != nil {
    log.Fatal(err)
}
Code in the following example defers Close to free the resource held by sql.Rows.

rows, err := db.Query("SELECT * FROM album WHERE artist = ?", artist)
if err != nil {
    log.Fatal(err)
}
defer rows.Close()

// Loop through returned rows.
As mentioned above, error events bubble. Error events are targeted at the request that generated the error, then the event bubbles to the transaction, and then finally to the database object. If you want to avoid adding error handlers to every request, you can instead add a single error handler on the database object, like so:

db.onerror = event => {
  // Generic error handler for all errors targeted at this database's
  // requests!
  console.error("Database error: " + event.target.errorCode);
};
Into main.go, beneath the import code you just added, paste the following Go code to create a database handle.

var db *sql.DB

func main() {
    // Capture connection properties.
    cfg := mysql.Config{
        User:   os.Getenv("DBUSER"),
        Passwd: os.Getenv("DBPASS"),
        Net:    "tcp",
        Addr:   "127.0.0.1:3306",
        DBName: "recordings",
    }
    // Get a database handle.
    var err error
    db, err = sql.Open("mysql", cfg.FormatDSN())
    if err != nil {
        log.Fatal(err)
    }

    pingErr := db.Ping()
    if pingErr != nil {
        log.Fatal(pingErr)
    }
    fmt.Println("Connected!")
}

Recommend

Go Opening a database handle Confirming a connection

Go Opening a database handle Opening a database handle Opening with a Connector

Go Opening a database handle Opening a database handle Opening with a connection string

Go Opening a database handle Locating and importing a database driver

Go Call your code from another module

Go Compile and install the application

Go Return greetings for multiple people

Tutorial: Get started with Go Call code in an external package

Tutorial: Get started with Go Write some code

Go Tutorial: Getting started with fuzzing Completed code

Go Tutorial: Getting started with fuzzing Fix the double reverse error Fix the error Run the code

Go Tutorial: Getting started with fuzzing Fix the double reverse error Fix the error Write the code

Go Tutorial: Getting started with fuzzing Fix the double reverse error Diagnose the error Run the code

Go Tutorial: Getting started with fuzzing Fix the double reverse error Diagnose the error Write the code

Go Tutorial: Getting started with fuzzing Fix the invalid string error Fix the error Run the code

Go Tutorial: Getting started with fuzzing Fix the invalid string error Fix the error Write the code

Go Tutorial: Getting started with fuzzing Fix the invalid string error Diagnose the error Run the code

Go Tutorial: Getting started with fuzzing Fix the invalid string error Diagnose the error Write the code

Go Tutorial: Getting started with fuzzing Fix the invalid string error Diagnose the error

Go Tutorial: Getting started with fuzzing Add a fuzz test Run the code

Go Tutorial: Getting started with fuzzing Add a fuzz test Write the code

Go Tutorial: Getting started with fuzzing Add a unit test Run the code

Go Tutorial: Getting started with fuzzing Add a unit test Write the code

Go Tutorial: Getting started with fuzzing Add code to test Run the code

Go Tutorial: Getting started with fuzzing Add code to test Write the code

Go Tutorial: Getting started with fuzzing Create a folder for your code

Tutorial: Create a Go module Start a module that others can use

Go Add a test

Go Return and handle an error

Go Return a random greeting

Go Tutorial: Getting started with multi-module workspaces Download and modify the golang.org/x/example module Future step

Go Tutorial: Getting started with multi-module workspaces Download and modify the golang.org/x/example module Run the code in the workspace

Go Tutorial: Getting started with multi-module workspaces Download and modify the golang.org/x/example module

Go Tutorial: Getting started with multi-module workspaces Create the workspace Initialize the workspace

Go Tutorial: Getting started with multi-module workspaces Create a module for your code