這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
package mainimport ("database/sql""fmt""strings")import (_ "github.com/mattn/go-adodb")type Mssql struct {*sql.DBdataSource stringdatabase stringwindows boolsa SA}type SA struct {user stringpasswd string}func (m *Mssql) Open() (err error) {var conf []stringconf = append(conf, "Provider=SQLOLEDB")conf = append(conf, "Data Source="+m.dataSource)if m.windows {// Integrated Security=SSPI 這個表示以當前WINDOWS系統使用者身去登入SQL SERVER伺服器(需要在安裝sqlserver時候設定),// 如果SQL SERVER伺服器不支援這種方式登入時,就會出錯。conf = append(conf, "integrated security=SSPI")}conf = append(conf, "Initial Catalog="+m.database)conf = append(conf, "user id="+m.sa.user)conf = append(conf, "password="+m.sa.passwd)m.DB, err = sql.Open("adodb", strings.Join(conf, ";"))if err != nil {return err}return nil}func main() {db := Mssql{dataSource: "CODY\\SQLEXPRESS",database: "test",// windwos: true 為windows身分識別驗證,false 必須設定sa帳號和密碼windows: true,sa: SA{user: "sa",passwd: "123456",},}// 串連資料庫err := db.Open()if err != nil {fmt.Println("sql open:", err)return}defer db.Close()// 執行SQL語句rows, err := db.Query("select * from info")if err != nil {fmt.Println("query: ", err)return}for rows.Next() {var name stringvar number introws.Scan(&name, &number)fmt.Printf("Name: %s \t Number: %d\n", name, number)}}