Search code examples
mysqlpowershellconnectionpowershell-3.0

Using PowerShell 3 to connect to MySQL DB


I've been scouring the internet for guides on how to do this, and most seem to tell me to do exactly what I'm doing already. All I'm trying to do is connect to a MySQL database and retrieve a name from the database based on a parameter I pass. The problem is that I've been unable to connect to the database based on all the guides I've seen so far.

Here's one of the ways I've tried:

$connectionstring = "server=mysql.collegename.edu;uid=sconsdoc;pwd=password;database=namedatabase;"

try {
    $connection = New-Object MySql.Data.MySqlClient.MySqlConnection
    $connection.ConnectionString = $connectionString
    $connection.Open()
} catch {
    Write-Host "ERROR : Unable to run query : $query 'n$Error[0]"
} finally {
    $connection.Close()
}

I get the following error:

ERROR : Unable to run query : 'nException calling "Open" with "0" argument(s): "Unable to connect to any of the specified MySQL hosts." Exception calling "Open" with "0" argument(s): "Unable to connect to any of the specified MySQL hosts." Exception calling "Open" with "0" argument(s): "Unable to connect to any of the specified MySQL hosts."[0]

I'm pretty sure I've specified the correct host, and I know I have the correct login credentials (I can at least log in through phpmyadmin), so I'm not sure what's wrong. I've followed the format I've seen in several guides so I don't understand what's wrong here. If I'm supposed to pass arguments to open, what are they? Like I said this is the only format I've been able to find to use.


Solution

  • "Unable to connect" sounds like a blocked connection attempt due to a closed/filtered port. Check if you can actually access the port on the remote server:

    telnet mysql.collegename.edu 3306
    

    If the database is listening on a non-default port you need to add the port to the connection string:

    server=mysql.collegename.edu;port=12345;uid=user;pwd=password;database=dbname;