1. 程式人生 > >windows下用golang連線mssql

windows下用golang連線mssql

我擦,最近下了幾十個G的資料(哈哈,你們懂的),都是mssql格式的,需要處理下。想用golang處理,於是就需要golang連線mssql。

1.安裝Microsoft SQL Server Native Client

去官方下載吧,下載地址:

http://www.microsoft.com/zh-CN/download/details.aspx?id=35580

2.安裝golang的mssql驅動

go get code.google.com/p/odbc

3.寫測試程式碼:

package main

import (
	_ "code.google.com/p/odbc"
	"database/sql"
	"fmt"
)

func main() {
	conn, err := sql.Open("odbc", "driver={sql server};server=192.168.1.1;port=1433;uid=sa;pwd=password;database=test")

	if err != nil {
		fmt.Println("Connecting Error")
		return
	}
	defer conn.Close()
	stmt, err := conn.Prepare("select top 5 id from users_role")
	if err != nil {
		fmt.Println("Query Error", err)
		return
	}
	defer stmt.Close()
	row, err := stmt.Query()
	if err != nil {
		fmt.Println("Query Error", err)
		return
	}
	defer row.Close()
	for row.Next() {
		var id int
		if err := row.Scan(&id); err == nil {
			fmt.Println(id)
		}
	}
	fmt.Printf("%s\n", "finish")
	return
}