osumatu
osumatu

Reputation: 442

C# connection.Open() exception

I am trying to connect to my database on localhost but for some reason, it throws an exception, and I can't find out why and where.

private void Initialize()
    {
        server = "localhost";
        database = "dbname";
        uid = "uname";
        password = "pass";
        string connectionString;
        connectionString = "SERVER=" + server + ";" + "DATABASE=" +
        database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";

        connection = new SqlConnection(connectionString);
    }

This is my initialize function; my problem is with:

    private bool OpenConnection()
    {
        try
        {
            connection.Open();
            return true;
        }
             ...

When I debug the program, it stays on "connection.Open();" line for a while, then I see "Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll" on console. But it's not crashing, just skipping.

Upvotes: 1

Views: 4164

Answers (2)

Steve
Steve

Reputation: 216243

If you want to open a connection with MySql, then you don't use the classes from System.Data.SqlClient namespace but with the classes from MySql.Data.MySqlClient

These classes are MySqlConnection, MySqlCommand, MySqlDataReader etc...
If you try to use the SqlConnection class you receive this error if the database to open is MySql because it can only work with the Sql Server, Sql Server Express or LocalDB database systems.

connection = new MySqlConnection(connectionString);

Of course, to use the MySql.Data.MySqlClient namespace you need to download and install the MySql NET Connector and then add a reference into your project to the assembly MySql.Data.dll (and add the using MySql.Data.MySqlClient to the top of each cs file that needs to use these classes)

Upvotes: 3

MBurnham
MBurnham

Reputation: 381

It is not crashing because you are opening the connection inside of a try-catch block, so the program thinks you are handling the exception. If you want it to crash, get rid of the try-catch block. (This would be a bad user experience.)

Alternatively, after your try-catch, you could check the connection is valid and then do something if it isn't.

if ((connection == null) || (connection.State != ConnectionState.Open)) { 
    /* do something here to indicate to the user there was an issue.
}

Upvotes: 0

Related Questions