Skip to main content

Command Palette

Search for a command to run...

Connecting to SQL Database with Go

Published
2 min read

The HTML and text templates, discussed in my previous few blog posts, are two of the many packages that become powerful tools when working with large datasets. Henceforth, my next series of blog posts will focus on working with SQL databases in Go. This blog post will go through the steps on how to connect to a SQL database.

Before writing the code, we need to import the database/sql package. This package must be used in conjunction with a SQL driver. In this tutorial, I will be connecting to SQL Server so github.com/microsoft/go-mssqldb will be imported. More SQL drivers can be found here and each can be installed with the go get command. I've also imported fmt for printing purposes:

import (
    "fmt",
    "database/sql",
    _ "github.com/microsoft/go-mssqldb"
)

Notice that I put the blank identifier, _, before the driver package name. This indicates that the imported package will not be used in the code itself. We import the driver so that it can be registered with the imported sql package. Note that when assigning an alias to an imported package in Go, the alias name comes before the imported package name.

Before connecting to any database, you need to create a connection string which usually requires the following credentials: the database server, name, username, and password.

func main() {

    connString := fmt.Sprintf("server=%s;user id=%s;
        password=%s;database=%s;Integrated Security=false;                                                                                            TrustedServerCertificate=True", server, user, password, db_name)

}

The next thing to do is to open the connection with the sql package we imported:

connection, error := sql.Open("mssql", connString)
if err != nil {
    fmt.Println("Could not connect to the database)
    panic(err)
}

The connection variable declared above is of type *sql.db as it points to a SQL connection.

After opening the connection, we can verify it and then close it. The defer keyword ensures that the database connection is closed regardless of how the function terminates (with or without error):

error := db.Ping()
if err != nil {
    fmt.Println("Could not verify connection to the database)
    panic(err)
}

defer connection.close()
Connecting to SQL Databases with Error Handling in Go