Invoke MySQL Query PowerShell

Hello,

Invoke MySQL query Powershell is quite easy once you get the prerequisites good.

Prerequisites

  1. MySQL dll
  2. ConnectionString or UserName, Password, Database and Server names

You can find the dll here :

http://dev.mysql.com/downloads/connector/net/1.0.html

MySql Data

MySql Data

For the connection information, ask your DBA, he will tell you.

Invoke MySQL Query PowerShell

Once you got the prerequisites you can start building your PowerShell code.

First, build your connection string :

$ConnectionString = “Server=$DataSource;uid=$UserName; pwd=$Password;Database=$database;Integrated Security=False;”

$DataSource is the IP address of your MySQL instance, $Username is the user name, $Password is the associated password and $Dtabase id the database name.

Second, import the MySQL DLL :

Import-Module C:TempMySql.Data.dll

Then, you can open a connection to your MySQL database :

$MySQLConnection = New-Object -TypeName MySql.Data.MySqlClient.MySqlConnection
$MySQLConnection.ConnectionString = $ConnectionString
$MySQLConnection.Open()

As soon as your connection to the database is open, you can query it :

$command     = New-Object MySql.Data.MySqlClient.MySqlCommand($query, $MySQLConnection)
$dataAdapter = New-Object MySql.Data.MySqlClient.MySqlDataAdapter($command)
$dataSet     = New-Object System.Data.DataSet
$recordCount = $dataAdapter.Fill($dataSet, 'data')
$dataSet.Tables['data']

And now the results flows in your PowerShell console.

Leave a Reply