package main import ( "database/sql" "fmt" "log" _ "github.com/mattn/go-adodb" ) // 连接 Microsoft SQL 结构体 type Mssql struct { *sql.DB } var ( mssql_data_source string = "10.6.132.21" mssql_database string = "gmistjj" mssql_user string = "epsoft" mssql_passwd string = "epsoft" mssql_port string = "1433" db Mssql ) func main() { name, err := GetName() if err != nil { fmt.Println(name) } } func (m *Mssql) GetSqlHandle() (err error) { if m.DB != nil { m.Close() log.Fatalf("关闭连接后从新连接~") } sql_conn_str := fmt.Sprintf("driver={sql server};server=%s;port=%s;uid=%s;pwd=%s;database=%s", mssql_data_source, mssql_port, mssql_user, mssql_passwd, mssql_database, ) m.DB, err = sql.Open("odbc", sql_conn_str) if err != nil { fmt.Println("链接失败!") return err } return nil } // 关闭数据库 func (m *Mssql) Close() (err error) { if m.DB == nil { return nil } err = m.DB.Close() m.DB = nil return } // 获取最近一期数据库数据 func GetName() (name string, err error) { // 连接数据库 err = db.GetSqlHandle() if err != nil { return } defer db.Close() sql_cmd := "select AB0111,AB0110,ZA9998,AA0177 from aa01 where AB0111 like '1105%' and AA010D='1' order by AB0110,AK010U" // 执行SQL语句 rows, err := db.Query(sql_cmd) if err != nil { return } defer rows.Close() // 释放连接池 img := Img{} for rows.Next() { rows.Scan(&img.AB0111, &img.AB0110, &img.ZA9998, &img.AA0177) fmt.Println(img) } return } type Img struct { AB0111 string AB0110 string ZA9998 string AA0177 string }