Go - connect remote SQL server
refer from:
https://studygolang.com/articles/19117
package sqlsvr
import (
"fmt"
"database/sql"
"strings"
"wms.api/model"
_ "github.com/denisenkom/go-mssqldb"
_ "github.com/mattn/go-adodb"
)
type Mssql struct {
*sql.DB
dataSource string
database string
windows bool
sa SA
}
type SA struct {
user string
passwd string
}
func (m *Mssql) Open() (err error) {
var conf []string
conf = 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 SignIn() int {
db := Mssql{
dataSource: `192.1.3.20\WMS`,
database: "SML",
// windwos: true 为windows身份验证,false 必须设置sa账号和密码
windows: false,
sa: SA{
user: "sa",
passwd: "raym",
},
}
// connect SQL
err := db.Open()
if err != nil {
fmt.Println("sql open:", err)
return 0
}
defer db.Close()
//SQL
rows, err := db.Query("SELECT date,name,time FROM dbo.WORK;")
if err != nil {
fmt.Println("query: ", err)
return 0
}
d := []model.Punch{}
for rows.Next(){
rd := model.Punch{}
rows.Scan(&rd.Date, &rd.Name, &rd.Time)
d = append(d,rd)
}
fmt.Println(d)
return 0
}
Comments
Post a Comment