无法连接到端口1433上的SQL Server数据库服务器

问题描述 投票:-1回答:2

我正在尝试为任务开始编写PowerShell SQL查询脚本,但在此之前我正在测试以确保我的数据库连接正常工作。

我已经使用SSMS 17在SQL Server中创建了一个表,并且作为连接测试的一部分,我正在测试是否可以在端口1433(也在防火墙规则中打开)上连接到数据库服务器。

这是我用来测试与SQL Server的端口连接的代码片段:

$port   = 1433

$tcp = New-Object Net.Sockets.TcpClient
if ([void]$tcp.Connect($dbhost, $port)) {
  'connected'
} else {
  'not connected'
}
$tcp.Dispose()

其中$dbhost = myservername.domain.com

每次我运行脚本时它都会返回:

未连接

这是为什么?

我检查了SSMS中的服务器产品及其使用情况

Microsoft SQL Server Enterprise: Core-based Licensing (64-bit)

我提到这个的原因是因为一些在线解决方案提到了服务器和实例,如果我有SQL Server Express,我必须将Express列为主机名或其他内容的一部分。但我有企业版而不是......所以我猜它的默认MSSQLServer不必指定为dbhostname的一部分

sql-server powershell tcp enterprise ssms-2017
2个回答
0
投票

Net.Sockets.TcpClient.Connect method返回void所以PowerShell if声明永远不会评估为$true。改为连接后检查Net.Sockets.TcpClient.Connected属性:

$port   = 1433

$tcp = New-Object Net.Sockets.TcpClient
$tcp.Connect($dbhost, $port)
if ($tcp.Connected) {
  'connected'
} else {
  'not connected'
}
$tcp.Dispose()

请注意,如果连接尝试失败,则会引发异常,因此if是多余的。你可以改用try / catch:

$port   = 1433

$tcp = New-Object Net.Sockets.TcpClient
try {
    $tcp.Connect($dbhost, $port)
    $tcp.Dispose()
    'connected'
} catch [System.Net.Sockets.SocketException] {
    $_.Exception.ToString()
    'not connected'
}

0
投票

您可能没有及时连接,但仍尝试检查当前状态是否已连接。尝试使用BeginConnect方法为Net.Sockets.TcpClient类它有超时选项,可能会帮助你。我已修复你的代码:

$port   = 1433
$timeout = 1000 #ms

$tcp = New-Object Net.Sockets.TcpClient
$wait = $tcp.BeginConnect($dbhost,$port,$null,$null)
[void]$wait.AsyncWaitHandle.WaitOne($timeout,$false)
if ($tcp.Connected) {
  'connected'
} else {
  'not connected'
}
$tcp.Close()
$tcp.Dispose()
© www.soinside.com 2019 - 2024. All rights reserved.