gpt4 book ai didi

powershell - Sql 命令(使用 "ExecuteScalar"参数调用 "0"时出现异常)

转载 作者:行者123 更新时间:2023-12-02 23:06:07 26 4
gpt4 key购买 nike

当我第一次尝试运行以下代码时,出现无法解释的错误,但第二次尝试再次运行该脚本工作正常...我的代码中会出现什么问题?

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

  $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

最佳答案

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

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

关于powershell - Sql 命令(使用 "ExecuteScalar"参数调用 "0"时出现异常),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2380354/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com