Sql命令(使用"0"参数调用"ExecuteScalar"的异常)

Ozi*_*arb 2 powershell powershell-2.0

当我第一次尝试运行下面的代码时,我得到一个无法解释的错误,但第二次尝试再次运行脚本工作正常......我的代码会出错?

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

  $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() 
Run Code Online (Sandbox Code Playgroud)

错误

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
Run Code Online (Sandbox Code Playgroud)

Gre*_*ray 5

如果您尝试使用服务器重置的连接执行命令,则会发生这种常见错误.每当我运行Powershell脚本,重新启动SQL Server,然后再次尝试运行脚本时,它始终发生在我身上.该脚本认为连接仍然是打开的,但是当它尝试使用它时,您会收到传输级错误并关闭连接.当您尝试再次运行脚本时,它将重新建立连接,一切正常.

如果要强制它关闭连接,只需在重新启动SQL Server时执行$ SqlConnection.Close()语句.