Golang链接MSSQL数据库

导入包

_ "github.com/denisenkom/go-mssqldb"
"database/sql"

链接参考代码

    //连接字符串 Go在连接Mssql数据库时踩的坑  连接字符串中 encrypt=disable 很重要
    connString := fmt.Sprintf("server=%s;user id=%s;password=%s;port=%d;database=%s;encrypt=disable",
        setting.MsSqlAddr, setting.MsSqlUserId, setting.MsSqlPassword, setting.MsSqlPort, setting.MsSqlDb)

    //建立连接
    conn, err := sql.Open("mssql", connString)
    if err != nil {
        setting.Logger.Errorf("Open Connection failed:", err.Error())
    }
    defer conn.Close()

    //产生查询语句的Statement 注意:库名与表名
    stmt, err := conn.Prepare(`select intTargetPort,varDesc,Addr,Longitude,Latitude,
    IsShangHai,IsHuNan from dbo.[tbAisDevice]`)
    if err != nil {
        setting.Logger.Errorf("Prepare failed:", err.Error())
    }
    defer stmt.Close()

    //通过Statement执行查询
    rows, err := stmt.Query()
    if err != nil {
        setting.Logger.Errorf("Query failed:", err.Error())
    }
    defer rows.Close()

    //遍历每一行
    var intTargetPort, IsShangHai, IsHuNan int
    var varDesc, Addr, Longitude, Latitude *string
    var itemList []bean.AisDevices
    for rows.Next() {
    //将查到的数据写入到这行中
        err := rows.Scan(&intTargetPort, &varDesc, &Addr, &Longitude, &Latitude, &IsShangHai, &IsHuNan) 
        if err != nil {
            setting.Logger.Errorf(err.Error())
        }
        dataItem := bean.AisDevices{
            IntTargetPort: intTargetPort,
            VarDesc:       varDesc,
            Addr:          Addr,
            Longitude:     Longitude,
            Latitude:      Latitude,
            IsShangHai:    IsShangHai,
            IsHuNan:       IsHuNan,
        }
    }