提问人:mnemotronic 提问时间:3/13/2017 最后编辑:mnemotronic 更新时间:7/21/2021 访问量:10170
golang SQL Server 查询 via go-mssqldb
golang SQL Server query via go-mssqldb
问:
我正在尝试使用 go 进行查询SQL Server 2008 R2
https://github.com/denisenkom/go-mssqldb。
SQL Server 2008 R2 实例位于 Windows Server 2008 R2 下的 VM 上;我正在 Win 7 VMWare 主机下进行开发,并从那里运行程序以查询 VM 上的数据库。数据库已启动并运行服务器 VM 上托管的应用。代码如下。
我收到的错误是:
[编辑2017-03-14:指定端口时出现新错误]
登录错误:读取 tcp 192.168.91.1:15222->192.168.91.135:1433: wsarecv:远程主机强行关闭了现有连接。
指定 SQL Server 端口 (1433) 时,将返回此错误。包含或不包括实例不会更改它。
SQL Server 配置为允许远程连接、SQL Server 身份验证、连接未加密、已启用 TCP/IP、IPALL 端口 = 1433。防火墙在 80、443、1433、1434 上为 TCP 打开;UDP 在 1433、1434 上。在将数据库实例添加到连接字符串之前,我遇到了不同的错误。
SQL Server 日志似乎表明计算机正在说话。IP 地址用于 VMWare 主机和 VM。SQL Server Browser 服务正在运行(帐户“本地服务”)。SQL Server 代理未运行。我尝试使用 ODBC 和 ADO 连接字符串,但似乎遇到了同样的错误。任何帮助将不胜感激。
package main
import (
// Import go-mssqldb strictly for side-effects
_ "github.com/denisenkom/go-mssqldb"
"database/sql"
"log"
)
func main() {
var n_tables int
println (sql.Drivers())
// URL connection string formats
// sqlserver://sa:mypass@localhost?database=master&connection+timeout=30 // username=sa, password=mypass.
// sqlserver://sa:my%7Bpass@somehost?connection+timeout=30 // password is "my{pass"
// note: pwd is "myP@55w0rd"
connectString := "sqlserver://SBM:myP%4055w0rd@VM17:1433?database=AE&connection+timeout=30"
println("Connection string=" , connectString )
println("open connection")
db, err := sql.Open("mssql", connectString)
defer db.Close()
println ("Open Error:" , err)
if err != nil {
log.Fatal(err)
}
println("count records in TS_TABLES & scan")
err = db.QueryRow("Select count(*) from ts_tables").Scan(&n_tables)
if err != nil {
log.Fatal(err)
}
println ("count of tables" , n_tables)
println("closing connection")
db.Close()
}
输出:
[2/2]0xc042002c20
Connection string= sqlserver://VM17_SBM:P%4055word@VM17:1433?database=VM17_SBM_AE_OE_REPO_CL&connection+timeout=30
open connection
Open Error: (0x0,0x0)
count records in TS_TABLES & scan
2017/03/14 19:48:01 Login error: read tcp 192.168.91.1:15222->192.168.91.135:1433: wsarecv: An existing connection was forcibly closed by the remote host.
exit status 1
答:
github 存储库如下
确保 SQL Server Browser Windows 服务正在运行,并且没有防火墙阻止 UDP 端口 1434。驱动程序使用此服务获取 SQL Server 实例的 TCP 端口
确保您的 SQLbrowser 服务正在您的主机上运行。
此外,还可以指定连接字符串以及端口号(如果您的端口是静态的,则无需启动 SQLBrowser 服务)
评论
read udp 192.168.91.1:49155->192.168.91.135:1434
为什么连接是udp
我在 Github 上图书馆作者的评论中找到了答案。
将“encrypt=disable”添加到连接字符串中就做到了。我正在按照此处的建议下载 SQL Server 2008 R2 x64 的 SP3 更新,并将在有时间时安装它。至于现在,虽然查询有效。
评论