Documentation Home
Connectors and APIs Manual
Download this Manual
PDF (US Ltr) - 4.5Mb
PDF (A4) - 4.5Mb

4.4.3 Handling Connection Errors

Because connecting to an external server is unpredictable, it is important to add error handling to your .NET application. When there is an error connecting, the MySqlConnection class will return a MySqlException object. This object has two properties that are of interest when handling errors:

  • Message: A message that describes the current exception.

  • Number: The MySQL error number.

When handling errors, you can adapt the response of your application based on the error number. The two most common error numbers when connecting are as follows:

  • 0: Cannot connect to server.

  • 1045: Invalid user name, user password, or both.

The following code example shows how to manage the response of an application based on the actual error:

C# Example

MySql.Data.MySqlClient.MySqlConnection conn;
string myConnectionString;
myConnectionString = "server=;uid=root;" +
    conn = new MySql.Data.MySqlClient.MySqlConnection(myConnectionString);
    catch (MySql.Data.MySqlClient.MySqlException ex)
    switch (ex.Number)
        case 0:
            MessageBox.Show("Cannot connect to server.  Contact administrator");
        case 1045:
            MessageBox.Show("Invalid username/password, please try again");

Visual Basic Example

Dim myConnectionString as String
myConnectionString = "server=;" _
          & "uid=root;" _
          & "pwd=12345;" _
          & "database=test"
    Dim conn As New MySql.Data.MySqlClient.MySqlConnection(myConnectionString)
Catch ex As MySql.Data.MySqlClient.MySqlException
    Select Case ex.Number
        Case 0
            MessageBox.Show("Cannot connect to server. Contact administrator")
        Case 1045
            MessageBox.Show("Invalid username/password, please try again")
    End Select
End Try

If you are using multilanguage databases then you must specify the character set in the connection string. If you do not specify the character set, the connection defaults to the latin1 character set. You can specify the character set as part of the connection string, for example:

MySqlConnection myConnection = new MySqlConnection("server=;uid=root;" +