go golang connect to mssql tutorial basic

  • 1522
  • 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

https://www.youtube.com/watch?v=nros7z5z-7M&list=PLFP7SbLMoK_Zl3EIgDbDBJkgyAjKivGR1&index=14

 

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

https://golang.org/pkg/database/sql/

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 (	
	"database/sql"
	_ "github.com/denisenkom/go-mssqldb"
}

 

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

Here is example of  go-mssqldb

https://github.com/denisenkom/go-mssqldb/tree/master/examples

 

and I think the most valuable example is tsql example:

https://github.com/denisenkom/go-mssqldb/blob/master/examples/tsql/tsql.go

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.