Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test Database Connection is OK before con.Open()

I have created a generic Database handler class for my app.

Im using a local database so SqlCeConnection class is being used here.

What I would like to do is test that the Connection string is valid, so update the connection status to the user before I execute connection.Open();

lets say

 SqlCeConnection conn = new SqlCeConnection(connectionString);

 //so far we have only created the connection, but not tried to open it
 //Would be nice to update the UI to say that conn is OK
 conn.testConnection();

 conn.Open();

I was thinking of writing a method that attempts to open then close the connection, am I right in thinking this or is there a better way.

like image 361
IEnumerable Avatar asked Mar 31 '26 18:03

IEnumerable


2 Answers

testing for connectivity adds extra overhead. why not directly open connection and put the code inside Try-Catch

try
{
    conn.Open();
}
catch(SqlCeException ex)
{
    // output the error to see what's going on
    MessageBox.Show(ex.Message); 
}
like image 155
John Woo Avatar answered Apr 02 '26 09:04

John Woo


You can use DbConnectionStringBuilder with property ConnectionString, it will throw exception if connection string is not correct format:

public static class Extension
{
    public static void TestConnection(this DbConnection connection)
    {
        var builder = new DbConnectionStringBuilder
            {
                ConnectionString = connection.ConnectionString
            };
    }
}

With this way you don't need to really open connection to database.

like image 41
cuongle Avatar answered Apr 02 '26 07:04

cuongle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!