HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Test connection to database C#

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
databasetestconnection

Problem

I've created a small method to test the connection to a database:

public bool TestConnection(string provider, string serverName, string initialCatalog, string userId, string password, bool integratedSecurity)
{
    var canConnect = false;

    var connectionString = integratedSecurity ? string.Format("Provider={0};Data Source={1};Initial Catalog={2};Integrated Security=SSPI;", provider, serverName, initialCatalog) 
                                              : string.Format("Provider={0};Data Source={1};Initial Catalog={2};User ID={3};Password={4};", provider, serverName, initialCatalog, userId, password);

    var connection = new OleDbConnection(connectionString);

    try
    {
        using (connection)
        {
            connection.Open();

            canConnect = true;
        }
    }
    catch (Exception exception)
    {

    }
    finally
    {
        connection.Close();                
    }                                         

    return canConnect;
}


Despite the method works it doesn t seems right to me. Is any way to test the connection without having to catch the exception?
Is it possible to achieve the same result in a different way?

Solution

It's a little verbose.

I would write

try {
    using(var connection = new OleDbConnection(...)) {
        connection.Open();
        return true;
    }
} catch {
    return false;
}


You should also use OleDbConnectionStringBuilder to properly escape the variables in the connection string.

Code Snippets

try {
    using(var connection = new OleDbConnection(...)) {
        connection.Open();
        return true;
    }
} catch {
    return false;
}

Context

StackExchange Code Review Q#5930, answer score: 14

Revisions (0)

No revisions yet.