我正在玩Golang
并尝试连接到MS SQL。我正在使用github.com/denisenkom/go-mssqldb
包和sqlx
来实现此目的。
但我收到错误:Unable to open tcp connection with host 'localhost:1433': dial tcp [::1]:1433: connectex: No connection could be made because the target machine actively refused it
我完全确定数据库本身的一切,因为它与my.Net项目完美配合。
这是代码:
package main
import (
"database/sql"
"fmt"
"log"
_ "github.com/denisenkom/go-mssqldb"
"github.com/jmoiron/sqlx"
)
type Excursion struct {
Id int `db:"id"`
Name sql.NullString `db:"name"`
}
func main() {
db, err := sqlx.Connect("sqlserver", "server=localhost;user id=DESKTOP-H74S9IT\\andrey.shedko;database=Flex;connection timeout=30;")
if err := db.Ping(); err != nil {
log.Fatal(err)
}
rows, err := db.Queryx("SELECT Id, Name FROM dbo.Excursions")
for rows.Next() {
var item Excursion
err = rows.StructScan(&item)
if err != nil {
log.Fatal(err)
}
fmt.Printf(
"%d - %s: %s\n===================\n",
item.Id,
item.Name.String,
)
}
defer db.Close()
}
你能告诉我这有什么问题吗?
答案 0 :(得分:3)
可能你需要激活TCP。
更多信息:Enable TCP/IP Network Protocol for SQL Server
图片来源:https://docs.microsoft.com/en-us/azure/includes/media/virtual-machines-sql-server-connection-tcp-protocol/enable-tcp.png和https://docs.microsoft.com/en-us/azure/includes/media/virtual-machines-sql-server-connection-tcp-protocol/restart-sql-server.png