Skip to content

Instantly share code, notes, and snippets.

@ptflp
Created June 26, 2018 14:45
Show Gist options
  • Save ptflp/da75369c7902f96d3a3ce741db6c33b4 to your computer and use it in GitHub Desktop.
Save ptflp/da75369c7902f96d3a3ce741db6c33b4 to your computer and use it in GitHub Desktop.
Using MySQL from powershell
Param(
[Parameter(
Mandatory = $true,
ParameterSetName = '',
ValueFromPipeline = $true)]
[string]$Query
)
$MySQLAdminUserName = 'USER'
$MySQLAdminPassword = 'PASSWORD'
$MySQLDatabase = 'MYDBNAME'
$MySQLHost = 'MYHOSTNAME'
$ConnectionString = "server=" + $MySQLHost + ";port=3306;uid=" + $MySQLAdminUserName + ";pwd=" + $MySQLAdminPassword + ";SslMode=none;database="+$MySQLDatabase
Try {
[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")
$DataSet.Tables[0]
}
Catch {
Write-Host "ERROR : Unable to run query : $query `n$Error[0]"
}
Finally {
$Connection.Close()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment