利用MySQL查询结果

时间:2013-07-12 10:22:43

标签: mysql powershell

需要帮助解决此问题: 我需要从MySQL DB获取表数据以便在脚本中进一步使用。我使用此代码访问MySQL数据:

[void][System.Reflection.Assembly]::LoadFrom("C:\Program Files (x86)\MySQL\MySQL Connector Net 6.7.4\Assemblies\v2.0\MySql.Data.dll")
$Connection = New-Object MySql.Data.MySqlClient.MySqlConnection
$Connection.ConnectionString = $ConnectionString
$Connection.Open()
$Command = New-Object MySql.Data.MySqlClient.MySqlCommand($Query, $Connection)
$DataAdapter = New-Object MySql.Data.MySqlClient.MySqlDataAdapter($Command)
$DataSet = New-Object System.Data.DataSet
$RecordCount = $dataAdapter.Fill($dataSet,"data") | Out-Null
$Command.Dispose()
$Table=$DataSet.Tables["data"] | FT  -auto
$Connection.Close()
$Table

它给了我珍贵的垃圾:

TASKID TASKTYPE fistNAME secNAME STATUS
------ -------- -------- ------- ------
1111          1 Dep1                  0
2222          2 User321  Dep1         0

但是当我尝试时,例如将结果导出为CSV:

Export-Csv -Path "c:\test.csv" -InputObject $Table
我得到的只有:

#TYPE System.Object[]
"Count","Length","LongLength","Rank","SyncRoot","IsReadOnly","IsFixedSize","IsSynchronized"
"6","6","6","1","System.Object[]","False","True","False"

所以当我尝试解析变量中的数据时:

Write-Host $Table
foreach ($Task in $Table) {
    Write-Host $Task.TASKID
}
我得到的只有:

Microsoft.PowerShell.Commands.Internal.Format.FormatStartData
Microsoft.PowerShell.Commands.Internal.Format.GroupStartData
Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData
Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData
Microsoft.PowerShell.Commands.Internal.Format.GroupEndData
Microsoft.PowerShell.Commands.Internal.Format.FormatEndData

有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:6)

这一行

$Table=$DataSet.Tables["data"] | FT  -auto

将您的数据转换为FormatStartData个对象的数组。

要导出数据时,请勿将数据导入Format-Table。试试这个:

$DataSet.Tables["data"] | Export-Csv "c:\test.csv"