How to query a MS SQL Server database in Go, (Golang)

Assumptions: That you have Go installed on your machine. That your GOPATH and GOROOT variables are set, and you have a Go work space. For instance I work out of c:\go-work. Moving on.

Open a text editor and save a file in your work space as example.go , I use Visual Studio Code and the Go (language support) and TabNine package (for amazing intellisense). You don’t need these though for the article, this is just advice to make life easier.

Basic structure of your Go file, example.go

Copy this code into the example.go. This is the very basic requirement of a go executable program, it won’t do anything like this but this is all that is required to build a working program for Linux, Mac OS or Windows, etc. More on that later.

package main //required of any executable program

// where our program begins
func main() {
   //the action
}

There are a few prerequisites for querying a database in Go. Besides the native Go packages we will import one other Go package. In case you didn’t know already Go can import from the source packages as well as from URLs.

In order to import our packages we will add an import statement below the “package main”. Notice there are no commas separating the lines, part of Go’s production focused design.

package main //required of any executable program

import ( //our Go packages for this project
    "database/sql"
    "fmt"	
    "log"
    _"github.com/denisenkom/go-mssqldb"
)


// where our program begins
func main() {
   //the action
}

For the database connection and handling I will add comments so you can step through and see what they do. Notice in the code, there is only one error handler for any of it. Again, Go was designed for production, speed and efficiency. This is in contrast to the code I typically see as a c# programmer where, as with anything, there are a million ways it has been done and sometimes the readability depends heavily on the artistic mood of the author at the time.

package main //required of any executable program

import ( //our Go packages for this project
    "database/sql"
    "fmt"	
    "log"
    _"github.com/denisenkom/go-mssqldb"
)


// where our program begins
func main() {
    //connect to the database
    db, err := sql.Open("sqlserver", "sqlserver://[username]:[password]@[host]?database=[database]&connection+timeout=30")
	if err != nil {
		log.Fatal(err)
        }
     //execute the query for ftp paths
    rows, err := db.Query("select @@version as 'version'")
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()

      //capture the results 
	vrs:= make([]*version, 0)
	for rows.Next() {
		vr:= new(vrs)
		err := rows.Scan(&vr.version)
		if err != nil {
			log.Fatal(err)
		}
		vrs= append(vrs, vs)
	}
	if err = rows.Err(); err != nil {
		log.Fatal(err)
	}
      //Print the rows
	for _, vs:= range vrs{
		fmt.Printf("%s\n", vs.version)
	}

	fmt.Println("Press the Enter Key to terminate the console screen!")
	fmt.Scanln() // wait for Enter Key
}

For windows, in a command terminal run: set GOOS=windows, set GOARCH=386, Go build example.go.

In the workspace directory you will now have a .exe file that when you run should spit out something similar, depending on your version of SQL Server.

Microsoft SQL Server 2014 - 12.0.2000.8 (Intel X86) 
	Feb 20 2014 19:20:46 
	Copyright (c) Microsoft Corporation
	Express Edition on Windows NT 6.3 <X64> (Build 9600: ) (WOW64) (Hypervisor)

A curated list of awesome Go frameworks, libraries and software