MySQL connection with Powershell

Posted by & filed under , .

Here is the script that establishing a connection to the Mysql database with ‘select statement’

  Mandatory = $true,
  ParameterSetName = '',
  ValueFromPipeline = $true)]
$ConnectionString="This is your connection string"
Try {
  $Con = New-Object MySql.Data.MySqlClient.MySqlConnection
  $Con.ConnectionString = $ConnectionString
  $MySqlCommand= New-Object MySql.Data.MySqlClient.MySqlCommand($Query, $Con)
  $DataAdapter = New-Object MySql.Data.MySqlClient.MySqlDataAdapter($MySqlCommand)
  $DataSet = New-Object System.Data.DataSet
  $RecordCount = $DataAdapter.Fill($DataSet,"data")
  $DataSet.Tables["data"] | Format-Table
Catch {
  Write-Host "Exception: $Query `n$Error[0]"
Finally {

If you take an error from the dll , after the try statement you can load the another mySql dll like this.

[void][system.reflection.Assembly]::LoadFrom(“C:\Program Files (x86)\MySQL\MySQL Connector Net\MySQL.Data.dll”)

Finally you can save this script and run!

.\mySqlConnection.ps1 -Query "select * from customers where bla bla "