我正在尝试从Power Shell运行SQL(位于我的Windows 7 64位桌面上),远程数据库主机是MS SQL Server 2012.
代码是:
$Server= ".\DB_HOST_NAME"
$Database = "master"
$UserSqlQuery= $("select count(*) from [master].[sys].[some_table]")
# executes a query and populates the $datatable with the data
function ExecuteSqlQuery ($Server, $Database, $SQLQuery) {
$Datatable = New-Object System.Data.DataTable
$Connection = New-Object System.Data.SQLClient.SQLConnection
$Connection.ConnectionString = "server='$Server';database='$Database';trusted_connection=true;"
$Connection.Open()
$Command = New-Object System.Data.SQLClient.SQLCommand
$Command.Connection = $Connection
$Command.CommandText = $SQLQuery
$Reader = $Command.ExecuteReader()
$Datatable.Load($Reader)
$Connection.Close()
$Datatable
return $Datatable
}
# declaration not necessary, but good practice
$resultsDataTable = New-Object System.Data.DataTable
$resultsDataTable = ExecuteSqlQuery $Server $Database $UserSqlQuery
Write-Host "Statistic: " $resultsDataTable
Write-Host "Message: Transaction Delay is " $resultsDataTable.Rows.Count
当我从Windows PowerShell运行时,出现以下错误:
异常通话"打开"用" 0"参数:"网络相关或 建立连接时发生特定于实例的错误 SQL Server。服务器未找到或无法访问。校验 实例名称正确且SQL Server配置为 允许远程连接。 (提供者:SQL网络接口,错误:26 - 找到指定的服务器/实例时出错)"在H:\ test2.ps1:11 char:5 + $ Connection.Open() + ~~~~~~~~~~~~~~~~~~ + CategoryInfo:NotSpecified:(:) [],MethodInvocationException + FullyQualifiedErrorId:SqlException
异常调用" ExecuteReader"用" 0"参数:" ExecuteReader 需要一个开放且可用的连接。连接的当前 国家关闭。"在H:\ test2.ps1:15 char:5 + $ Reader = $ Command.ExecuteReader() + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo:NotSpecified:(:) [],MethodInvocationException + FullyQualifiedErrorId:InvalidOperationException
异常调用"加载"用" 1"参数:"值不能为空。 参数名称:dataReader"在H:\ test2.ps1:16 char:5 + $ Datatable.Load($ Reader) + ~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo:NotSpecified:(:) [],MethodInvocationException + FullyQualifiedErrorId:ArgumentNullException
所以第一个错误发生在$Connection.Open()
但是我对电源外壳一无所知,以找出问题所在。我尝试在同一个数据库主机上运行相同的SQL,它确实返回一个数字。
我可以帮助了解我在这里做错了什么吗?
答案 0 :(得分:1)
此代码:
$Server= ".\DB_HOST_NAME"
应该是:
$Server= "DB_HOST_NAME"
规范"。\ DB_HOST_NAME"被解释为在本地框上运行的命名实例(DB_HOST_NAME)。