Member-only story
Setting up an SQL connection in Go
Setting up an SQL connection in Go is simple, thanks to Go’s database/sql
package, which provides a standard interface for working with SQL databases. Here's a step-by-step guide using MySQL as an example.
Step 1: Install the MySQL Driver
To use MySQL with Go, you’ll need to install a driver. The most commonly used MySQL driver is go-sql-driver/mysql
:
go get -u github.com/go-sql-driver/mysql
Step 2: Import the Required Packages
In your Go file, import the database/sql
package along with the MySQL driver:
import (
"database/sql"
"fmt"
"log"
_ "github.com/go-sql-driver/mysql"
)
The underscore before the MySQL driver package imports it solely for its initialization side effects, as it registers itself with database/sql
without being directly referenced in the code.
Step 3: Configure the Database Connection
Define the database connection string with the following format:
dsn := "username:password@tcp(127.0.0.1:3306)/dbname"
For example:
username
is your MySQL username.password
is your MySQL password.