代码之家  ›  专栏  ›  技术社区  ›  spicy.dll

sqlclient.executenonquery未返回行数

  •  2
  • spicy.dll  · 技术社区  · 8 年前

    我已经处理了一段时间了。我有一个简单的powershell函数,它接受到SQL服务器的开放连接和包含SQL命令的字符串,并在服务器上运行它。函数应返回一个整数值,表示已更新的行数。但是,它却输出有关该方法的信息。

    代码:

    function Invoke-MSSQLNonQuery () {
        param (
            [System.Data.SqlClient.SqlConnection]$Connection,
            [string]$Command
        )
    
        # Create the SQL Command Ojbect
        $SQLCommand = New-Object System.Data.SqlClient.SqlCommand
    
        # Set the Command Text and Connection for the Command
        $SQLCommand.CommandText=$Command
        $SQLCommand.Connection=$Connection
    
        # Run command and return the rows affected
        [int]($SQLCommand.ExecuteNonQuery | Out-String)
    }
    

    但是,在执行时,我得到以下错误:

    Cannot convert value "
    OverloadDefinitions
    -------------------
    int ExecuteNonQuery()
    int IDbCommand.ExecuteNonQuery()
    
    " to type "System.Int32". Error: "Input string was not in a correct format."
    At C:\_Local\playground\Mason\UpdateFromInventory.ps1:153 char:5
    +     [int]($SQLCommand.ExecuteNonQuery | Out-String)
    +     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidArgument: (:) [], RuntimeException
        + FullyQualifiedErrorId : InvalidCastFromStringToInteger
    

    我知道 ExecuteNonQuery ,当管道输送到 Out-String ,正在输出具有其重载定义的表:

    OverloadDefinitions
    ------------------- 
    int ExecuteNonQuery() 
    int IDbCommand.ExecuteNonQuery()
    

    我也尝试过不将其管道化到任何对象,这样在没有表头的情况下返回了类似的结果。

    编辑:另外,我应该提到,我95%确信sql命令执行成功。我肯定这个函数以前工作过一次,甚至返回正确的输出。然而,这种情况已经不长时间了。

    我的问题是:

    1. 为什么?
    2. 如何让它输出受影响的行数?
    1 回复  |  直到 8 年前
        1
  •  6
  •   Ansgar Wiechers    8 年前

    您试图调用不带括号的方法。在执行此操作时,语句将显示重载列表,而不是实际调用方法(请参见 here ,即使先将其转换为字符串,也不能将其强制转换为整数。

    改变

    [int]($SQLCommand.ExecuteNonQuery | Out-String)
    

    进入之内

    [int]$SQLCommand.ExecuteNonQuery()
    

    代码应该做你想做的。

    推荐文章