将SQL查询结果存储在变量

时间:2017-02-08 16:49:02

标签: mysql powershell powershell-v4.0

我不明白为什么将查询结果存储在变量中会如此困难。

当我运行此脚本而不尝试将结果存储在变量中时,我得到了正确的结果。但是,如果我尝试将相同的值存储在变量中,则变量的值为System.Data.DataRow。我已经尝试将其转换为字符串(崩溃脚本),$data_set.Tables[0].Rows[0]$data_set.Tables[0].Rows[0]["Value"],但仍然没有运气。打印结果是不够的,我需要根据查询结果进行更改。

我想要$max_slide_count = 910980

$slide_id_query = "SELECT MAX(SLIDE_ID) FROM INFOTECHSLIDES.SLIDES;"
try {
        Write-Host "Creating Database Connection"

        #ENABLE MYSQL DRIVER
        [System.Reflection.Assembly]::LoadWithPartialName("MySql.Data")

        #CREATE MYSQL CONNECTION
        $connection = New-Object MySql.Data.MySqlClient.MySqlConnection
        $connection.ConnectionString = $connection_string

        #OPEN DB CONNECTION
        Write-Host "Opening Database Connection"
        $connection.Open()

        #RUN MYSQL QUERY
        $command = New-Object MySql.Data.MySqlClient.MySqlCommand($slide_id_query, $connection)
        $data_adapter = New-Object MySql.Data.MySqlClient.MySqlDataAdapter($command)
        $data_set = New-Object System.Data.DataSet
        $record_count = $data_adapter.Fill($data_set, "data")

        #STORE RESULT
        $max_slide_count = $data_set.Tables[0]

        $data_set.Tables[0]                   #RETURNS: MAX(SLIDE_ID) : 910980
        Write-Host "Result: $max_slide_count" #RETURNS: System.Data.DataRow

} catch {
        Write-Host "Could not execute MySql Query" $Error[0]
}

1 个答案:

答案 0 :(得分:0)

您需要从行中获取该项目。
$max_slide_count = $data_set.Tables[0].Rows[0].Item("MAX(SLIDE_ID)")