Sql 命令(使用“0”参数调用“ExecuteScalar”时出现异常)

发布于 2024-08-24 00:52:16 字数 1011 浏览 6 评论 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() 

错误

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

When I run the below code on first attempt I get an unexplained error, but running the script again on a second attempt works fine...what would be wrong in my code?

By the way I am creating the database before this step...

  $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() 

Error

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

稳稳的幸福 2024-08-31 00:52:16

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

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

That is a common error that occurs if you try to execute a command using a connection that was reset by the server. It happens to me all the time whenever I run a Powershell script, restart the SQL Server, and then try and run the script again. The script thinks that the connection is still open, but when it tries to use it you get a transport-level error and it closes the connection. When you try to run the script again it will re-establish the connection and everything works fine.

If you want to force it to close the connection simply execute the $SqlConnection.Close() statement whenever you restart the SQL server.

卖梦商人 2024-08-31 00:52:16

对于我遇到的奇怪情况,我最终找到了一个可接受的解决方案,使用 $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()
      }
  }

For my strange case that I had I finally came to an acceptable solution by using $error variable instead of ($LastExitCode or $?) to detect sql query failure and loop for couple of attempts as my code works after second attempt.

$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()
      }
  }
痴情 2024-08-31 00:52:16

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

Have you checked the SQL Server Configuration Manager to make sure that "Named Pipes" is enabled (under "SQL Server Network Configuration -> Protocols for SQL...")?

相思故 2024-08-31 00:52:16

我认为你可以强制它直接进入 tcp(1433) 并通过使用

“Server=$dBServer,1433;Database=$dBName;Integrated Security=True”

跳过建立命名管道连接许多库、客户端首先尝试命名管道,但是通常,最佳做法是仅让 1433 侦听您的目标。我认为 Ozie 的代码也可以工作...很简单,尝试命名管道,失败,尝试 1433,这是 MS 事物经常工作的标准方式。您可以尝试使用网络库等进行 Fussign,正如其他人所描述的那样,但使​​用正确的 conn 字符串通常是一个好主意,这样您就知道您用于防火墙等的端口。

I think you can force it go straight to tcp(1433) and skip making a named pipes connection by using

"Server=$dBServer,1433;Database=$dBName;Integrated Security=True"

Many libraries,clients try named pipes first, but typically best practice is only to have 1433 listening on your target. I think the Ozie's code works too...it is simple trying named pipes, failing, trying 1433 which is the standard way MS things often work. You could try fussign with network libaries etc as others have described, but using the right conn string is typically a good idea so you know which port you are using for firewalls etc.

眉黛浅 2024-08-31 00:52:16

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

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

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

I had this same issue, I managed to resolve it by moving the connection string to the same line where the connection is instantiated.

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

Not sure why, but assigning it afterwards does not work. Perhaps someone can shed some light on the why?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文