programming.torensma.net: Code Snippets

Connect PowerShell to MySQL

Using the MySQL.NET connector, it’s possible to connect to a MySQL database using PowerShell.

/* replace path with your local /path/to/mysql/connector/MySQL.Data.dll */
[void][system.reflection.Assembly]::LoadFrom(\"d:\\tools\\mysql-connector\\bin\\MySQL.Data.dll\")

$myconnection = New-Object MySql.Data.MySqlClient.MySqlConnection
$myconnection.ConnectionString = \"server=localhost;user id=test;password=test;database=test;pooling=false\"
$myconnection.Open()

$mycommand = New-Object MySql.Data.MySqlClient.MySqlCommand
$mycommand.Connection = $myconnection
$mycommand.CommandText = "SHOW TABLES"

$myreader = $mycommand.ExecuteReader()

while($myreader.Read()){ $myreader.GetString(0) }

This example will display all tables in the connected database.

  • What’s the best way to use powershell to create a script to restore a mysql DB from a sql dump? – Arunabh Das

  • The easiest way is probably to use mysqlimport. This command-line app is installed with mysql, and is specifically made to import files created by mysqldump. Personally I would do this with an old-fashioned batch file. PowerShell seems a bit over-powered for this… Good luck!

You can follow any responses to this entry through the RSS 2.0 feed.

Trackbacks / Pingbacks