mysql – 结果集是1个记录的对象,数组是多少?
作者:互联网
我无法相信,但所有迹象都表明我的PowerShell代码返回SELECT查询的结果,该查询找到1条记录作为对象,但如果有两条或更多条记录,则相同的代码返回一个对象数组.我究竟做错了什么?
以下是代码:
function Connect-MySQL([string]$MySQLHost, [string]$user, [string]$pass, [string]$database) {
Write-Verbose "Connect-MySQL"
# Load MySQL .NET Connector Objects
[void][system.reflection.Assembly]::LoadWithPartialName("MySql.Data")
# Open Connection
$connStr = "server=$MySQLHost;port=3306;uid=$user;pwd=$pass;database=$database;Pooling=FALSE"
try {
$con = New-Object MySql.Data.MySqlClient.MySqlConnection($connStr)
$con.Open()
} catch [System.Management.Automation.PSArgumentException] {
Write-Verbose "Unable to connect to MySQL server, do you have the MySQL connector installed..?"
Write-Verbose $_
Exit
} catch {
Write-Verbose "Unable to connect to MySQL server..."
Write-Verbose $_.Exception.GetType().FullName
Write-Verbose $_.Exception.Message
exit
}
Write-Verbose "Connected to MySQL database $MySQLHost\$database"
return $con
}
function Disconnect-MySQL($con) {
Write-Verbose "Disconnect-MySQL"
$con.Close()
}
function Execute-MySQLNonQuery($con, [string]$sql) {
$cmd = New-Object MySql.Data.MySqlClient.MySqlCommand($sql, $con) # Create SQL command
$Rows = $cmd.ExecuteNonQuery() # Execute command
$cmd.Dispose() # Dispose of command object
# if ($Rows) {
return $Rows
# } else {
# return $false
# }
}
function Execute-MySQLQuery($con, [string]$sql) {
$cmd = New-Object MySql.Data.MySqlClient.MySqlCommand($sql, $con) # Create SQL command
$dataAdapter = New-Object MySql.Data.MySqlClient.MySqlDataAdapter($cmd) # Create data adapter from query command
$dataSet = New-Object System.Data.DataSet # Create dataset
$dataAdapter.Fill($dataSet, "data") | Out-Null # Fill dataset from data adapter, with name "data"
$cmd.Dispose() # Dispose of command object
return $dataSet.Tables["data"] # Returns an array of results
}
# Connection Variables
$MySQLHost = '10.10.10.111'
$user = 'user'
$pass = 'test'
$database = 'test_db'
# Connect to MySQL Database
$con = Connect-MySQL $MySQLHost $user $pass $database
# Get requests
$sql = "
SELECT *
FROM o365_statuses as x
WHERE x.action = 'Z'
AND x.status = 0"
$result = Execute-MySQLQuery $con $sql
Write-Host $result.Count
Foreach ($r in $result) {
write-host "$($r.id) $($r.email)"
}
当$result只有1条记录时,$result.Count不返回任何内容,我可以将这些列作为$result.id而不是$result [0] .id访问.如果返回2条或更多条记录则相反.
请告诉我,我做错了,这不是PowerShell的工作方式.
解决方法:
PowerShell基于这个简单的算法返回结果:
>多个项目 – >返回这些项的数组
>只有一个项目 – >退货
通常,强制PowerShell始终使用以下任一方法返回数组是一种好习惯:
,(code)
@(code)
但是,这些操作符并不完全相同!您可以安全地将@()分组运算符应用于强制数组输出的任何内容 – 数组始终具有Count属性,例如:
$a = @(Get-Process | select -First 2); $a.Count # returns 2
$a = @(Get-Process | select -First 1); $a.Count # returns 1
另一方面,逗号数组构造运算符的工作方式如下:
$a = ,(Get-Process | select -First 2); $a.Count # returns 1
$a = ,(Get-Process | select -First 1); $a.Count # returns 1
…因为它使用给定的任何内容构建嵌套数组.
标签:mysql,powershell,dataset,dataadapter 来源: https://codeday.me/bug/20190620/1247200.html