爲了可以使用linux下golang環境鏈接sqlserver 2008查了不少資料,最終採用unixodbc freetds等鏈接成功。linux
運行如下shellgit
#!/bash/bin sudo apt-get update && sudo apt-get upgrade -y sudo apt-get install unixodbc unixodbc-bin unixodbc-dev freetds-bin freetds-dev tdsodbc -y echo "=================================================================" echo "[FreeTDS] Description = FreeTDS Driver v0.91 Driver = /usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so Setup = /usr/lib/x86_64-linux-gnu/odbc/libtdsS.so fileusage=1 dontdlclose=1UsageCount=1client charset=utf-8" | sudo tee -a /etc/odbcinst.iniecho "[testdb]Driver = FreeTDS Description = My Test Server Trace = No ServerName = demosql #這裏對應下面的freetds.conf中的名稱 Port = 1433Database = db_demo #修改成你須要鏈接的數據庫名稱 TDS_Version = 7.2" | sudo tee -a /etc/odbc.iniecho "[demosql]host =192.168.1.1 #這裏填寫本身的數據庫地址 Port = 1433tds version = 7.2 #鏈接sql2008,根據freetds官方網站說法,能夠使用7.2版本 #http://www.freetds.org/userguide/choosingtdsprotocol.htm " | sudo tee -a /etc/freetds/freetds.confecho "================================================================="echo "isql -v testdb username passwd"
完成後利用 isql -v DSN名稱 用戶名 密碼進行鏈接測試github
測試成功後下載go所需的odbc包golang
go get -v -u github.com/weigj/go-odbc
接下來編寫一個測試程序:sql
package main import ( "fmt" "github.com/weigj/go-odbc" ) func main() { conn, _ := odbc.Connect("DSN=testdb;UID=sa;PWD=password") stmt, _ := conn.Prepare("select top 10 * from studentinfo") stmt.Execute() rows, _ := stmt.FetchAll() for i, row := range rows { fmt.Println(i, row) } stmt.Close() conn.Close() }
結果:shell
[ `run` | done: 20.224378ms ] 0 &{[28]} 1 &{[23]} 2 &{[42]} 3 &{[23]} 4 &{[24]} 5 &{[25]} 6 &{[32]} 7 &{[42]} 8 &{[35]} 9 &{[30]}