2

当我第一次尝试运行以下代码时,我得到一个无法解释的错误,但在第二次尝试时再次运行脚本工作正常......我的代码有什么问题?

顺便说一句,我在这一步之前创建数据库......

  $SqlConnection = New-Object System.Data.SqlClient.SqlConnection
  $SqlConnection.ConnectionString = "Server=$dBServer;Database=$dBName;Integrated Security=True" 
  $SqlConnection.Open() 

  $SqlCmd = New-Object System.Data.SqlClient.SqlCommand 
  $SqlCmd.CommandText = $dBCmd 
  $SqlCmd.Connection = $sqlConnection 

  $execute = $SqlCmd.ExecuteScalar() 
  $SqlConnection.Close() 

错误

Exception calling "ExecuteScalar" with "0" argument(s): "A transport-level error has occurred when sending the request to the server. (provider: Shared Memory  Provider, error: 0 - No process is on the other end of the pipe.)" At c:\scripts\DB\Powershell\RunSql.ps1:61 char:34
+   $execute = $sqlCmd.ExecuteScalar <<<< ()
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException
4

5 回答 5

5

如果您尝试使用由服务器重置的连接执行命令,则会发生这种常见错误。每当我运行 Powershell 脚本、重新启动 SQL Server,然后再次尝试运行脚本时,都会发生这种情况。该脚本认为连接仍处于打开状态,但当它尝试使用它时,您会收到传输级错误并关闭连接。当您尝试再次运行脚本时,它将重新建立连接并且一切正常。

如果您想强制它关闭连接,只需在重新启动 SQL 服务器时执行 $SqlConnection.Close() 语句。

于 2010-03-05T00:08:09.393 回答
0

对于我的奇怪情况,我终于找到了一个可以接受的解决方案,方法是使用 $error 变量而不是 ($LastExitCode 或 $?) 来检测 sql 查询失败并循环几次尝试,因为我的代码在第二次尝试后工作。

$attempts = 0
$maxAttempts = 3

  while ($attempts -lt $maxAttempts)
  {
    $attempts++
    $error.clear() # Clears teh error variable incase of any previous errors in the script

      $SqlConnection = New-Object System.Data.SqlClient.SqlConnection 
      $SqlConnection.ConnectionString = "Server=$dBServer;Database=$dBName;Integrated Security=True"  
      $SqlConnection.Open()  

      $SqlCmd = New-Object System.Data.SqlClient.SqlCommand  
      $SqlCmd.CommandText = $dBCmd  
      $SqlCmd.Connection = $sqlConnection  

      $execute = $SqlCmd.ExecuteScalar()  
      $SqlConnection.Close()  

      if ($error.count -eq 0)
      {
        write-host "Sql Query was Successful."            
        break
      }        

      else
      {   
        write-host "Sql Query failed on attempt $attempts"
        $error.clear()
      }
  }
于 2010-03-05T16:31:06.200 回答
0

您是否检查过 SQL Server 配置管理器以确保启用了“命名管道”(在“SQL Server 网络配置 -> SQL 的协议...”下)?

于 2010-03-04T16:33:52.580 回答
0

我认为您可以强制它直接进入 tcp(1433) 并通过使用跳过建立命名管道连接

“服务器=$dBServer,1433;数据库=$dBName;集成安全=True”

许多图书馆,客户首先尝试命名管道,但通常最好的做法是只让 1433 监听你的目标。我认为 Ozie 的代码也可以工作......尝试命名管道很简单,失败,尝试 1433,这是 MS 通常工作的标准方式。您可以尝试使用其他人描述的网络库等进行 fussign,但使用正确的 conn 字符串通常是一个好主意,因此您知道您将哪个端口用于防火墙等。

于 2012-03-20T22:50:39.747 回答
0

我遇到了同样的问题,我设法通过将连接字符串移动到实例化连接的同一行来解决它。

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection $conString

不知道为什么,但事后分配它不起作用。也许有人可以解释为什么?

于 2017-01-19T14:59:13.123 回答