PowerShell不会逐行迭代MySQL结果 - 为什么?

时间:2015-10-10 14:41:53

标签: mysql loops powershell line

我使用以下代码使PowerShell打印出SQL-SELECT的结果......

[String] $mySQlServerName = "localhost";
[String] $mySQLDatenbankName = "test";
[String] $userName = "root";
[String] $password = "";

$mySqlConnection = New-Object MySql.Data.MySqlClient.MySqlConnection;

$mySqlConnection.ConnectionString = "server=$mySQlServerName;user id=$userName;password=$password;database=$mySQLDatenbankName;pooling=false";

$mySqlConnection.Open();

$mySqlCommand = New-Object MySql.Data.MySqlClient.MySqlCommand;

$mySqlCommand.Connection = $mySqlConnection;

$mySqlCommand.CommandText = "SELECT SourceIPO1, SourceIPO2, SourceIPO3, SourceIPO4, rejections FROM test.malicious_apache;";

write-host $mySqlCommand.CommandText;

$reader = $mySqlCommand.ExecuteReader();

if ($reader -eq $null)
{
    write-host "no result";
}
else
{
    [int] $columnCount = $reader.VisibleFieldCount;
    write-host "$columnCount columns in result ...";

    while ($reader.Read())
    {
        write-output "next row";
        for ($i= 0; $i -lt $reader.VisibleFieldCount; $i++)
        {
            write-output $reader.GetValue($i).ToString()
        }
    }

    $reader.Close();
}

$mySqlConnection.Close();

获得以下输出......

PS C:\Users\Max> TestSelect.ps1
SELECT SourceIPO1, SourceIPO2, SourceIPO3, SourceIPO4, rejections FROM test.malicious_apache;
5 columns in result ...

使用mysql-client发出的SELECT提供了大约5,966行!作为一个PowerShell新手我很惊讶和困惑,这个代码在很多网站上使用,对我来说似乎是完全合理的,为什么我没有得到单个输出"下一行"?

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:2)

当比较运算符的左操作数是集合时,该运算符的结果不是布尔值,但包含所有元素的数组满足该比较运算符:

$a=1..5
$a -ne 3 # return array with four elements 1,2,4,5
$a -gt 3 # return array with two elements 4,5
$a -eq 3 # return array with one element 3
$a -lt 1 # return empty array

要评估该结果,PowerShell必须枚举集合。

DbDataReader实现IEnumerable,因此它被PowerShell视为集合。要评估$reader -eq $null表达式,PowerShell必须枚举$reader。由于该枚举$reader将提前到当前结果集的末尾,因此您无法读取更多行。要将集合与$null进行实际比较,您必须颠倒-eq运算符操作数的顺序:$null -eq $reader