go golang connect to mssql tutorial basic

  • 1161
  • 0
  • 2018-05-17

golang go connect to mssql

I describe my process of finding way to use go connect to mssql here.


First I find this turorial video, and I learn the basic concept of using go conncect to database



Then I find the database/sql doc of go here:


the key concept is:

Package sql provides a generic interface around SQL (or SQL-like) databases.

The sql package must be used in conjunction with a database driver. 
See https://golang.org/s/sqldrivers for a list of drivers.


That is if you want to connect to DB by go,

you have to use 2 things: 

1.the sql interface, that is the database/sql  package

2.the driver, list in https://github.com/golang/go/wiki/SQLDrivers

in the list, I choose go-mssqldb as example


So, you have to import these 2 package first, that is

import (	
	_ "github.com/denisenkom/go-mssqldb"


After knowing above, we can directly see the executable example,

Here is example of  go-mssqldb



and I think the most valuable example is tsql example:


if you want to let this example work,

you just need to configue your connection string at the top,

that is modify the example connection flag to

	var (
		userid   = flag.String("U", "yourDBuserId", "login_id")
		password = flag.String("P", "yourDBpassword", "password")
		server   = flag.String("S", "yourDBsevername", "server_name[\\instance_name]")
		database = flag.String("d", "yourDBname", "db_name")

then you can build and run to see the effect.

Also if you work with vscode, you can execute in debug mode and step into code line by line to experience the working detail.