PowerShell和MySQL - 保持连接打开多个查询?

时间:2016-06-16 18:05:08

标签: mysql powershell

我正在使用PowerShell的MySQL连接器,我需要进行查询,然后稍微擦洗数据,然后将余数转储到同一MySQL数据库上的另一个表中。我怎么能保持连接打开以使这一切运行得更快?

[void][System.Reflection.Assembly]::LoadWithPartialName("MySql.Data")
      $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")
      return $DataSet.Tables[0]

1 个答案:

答案 0 :(得分:0)

在调用此函数的函数中创建连接对象。被调用的函数将继承调用函数维护的任何对象,因此$Connection在被调用函数中有效。

function RunMe(){
    [void][System.Reflection.Assembly]::LoadWithPartialName("MySql.Data")
    $Connection = New-Object MySql.Data.MySqlClient.MySqlConnection
    $Connection.ConnectionString = $ConnectionString
    $Connection.Open()

    # Call the function that executes the MySQL code
    ExecuteMySQL

    # If needed, call another function that executes the MySQL code
    ExecuteSomeOtherMySQL

    # Close the connection after all MySQL operations are complete
    $Connection.Close()
}

function ExecuteMySQL(){
    $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")
    return $DataSet.Tables[0]
}