This is an article created on, where the information may have evolved or changed.
Go language accesses the SQL server through ODBC. The go-odbc library needs to be used here.
1. Driver installation
Open GOPATH in cmd:
Go to src directory
Get the odbc driver through git in the src directory:
git clone git: //github.com/weigj/go-odbc.git odbc
Go to the odbc directory:
Run the go install command:
Prompt that gcc compiler is not installed, go to the official website to download http://tdm-gcc.tdragon.net/
Second, install gcc
Or Download mingw-w64-install.exe (170.0 kB), restart after installation.
It is mingw-w64-install.exe (https://sourceforge.net/projects/mingw-w64/) installation process:
Configure the Gcc environment, open system variables, modify Path, add E: \ Program Files \ mingw-w64 \ x86_64-5.3.0-posix-seh-rt_v4-rev0 \ mingw64 \ bin, such as:
Run the go install command again, no error message is displayed, such as:
Third, the sample program
Idea: link to database-> create a query-> display query results
package main import ("database / sql"
"fmt" _ "odbc / driver") func main () {fmt.Printf ("% s \ n", "Create Database Link") conn, err: = sql.Open ("odbc", "Driver = {SQL Server}; SERVER =. \\ sql2008; UID = sa; PWD=admin@163.com; DATABASE = DTcmsdb4 ") if err! = Nil {fmt.Println (" Link error ") return} defer conn.Close () fmt.Printf ("% s \ n", "Build query") stmt, err: = conn.Prepare ("select id from dt_article") if err! = nil {fmt.Println ("Query exception:", err) return} defer stmt.Close () row, err: = stmt.Query () if err! = nil {fmt.Println ("Query error:", err)} defer row.Close () fmt.Printf ("% s \ n "," Data Set Display ") for row.Next () {var id int
if err: = row.Scan (& id); err == nil {fmt.Println (id)}} fmt.Printf ("% s \ n", "Complete query") return}
The problem is coming, run successfully through the command line:
When running through VSC, the following error is prompted:
Reason for analysis: My first go.go file and access-sqlserver.go in the D: \ GoWorks directory have main functions.
Solution: Modify the main function name in my first go.go file to maina.
During the commissioning, success:
In summary, in VSC, all files in the same directory are compiled.
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.