xplat
xplat

Reputation: 8626

Validate SQL Server Connection

How i could check if i have connection to an SQL Server with the Connection String known in C#?

Upvotes: 0

Views: 1110

Answers (4)

Braulio Nova
Braulio Nova

Reputation: 23

Check the state of the connection.

if (conexion.State == ConnectionState.Closed)
{
    conexion.Open();
}

Upvotes: 0

Gratzy
Gratzy

Reputation: 9389

I"m not sure if you are asking how to validate a connection string or check to see if a current connection is open If you are trying to check if a current connection is open you can use.

connection.State

ConnectionState Enumeration Values

Upvotes: 3

Sam
Sam

Reputation: 1514

You can also test it outside of your code by making an UDL file (a text file with extension .UDL). Then right-click it, get the properties and enter the connectionstring details.
Press the "Test Connection" button and then you'll know.

Upvotes: 1

František Žiačik
František Žiačik

Reputation: 7612

using (var connection = new SqlConnection("connectionString"))
{
    try
    {
        connection.Open();
        Console.WriteLine("Connection Ok");
    }
    catch (SqlException)
    {
        Console.WriteLine("Connection Not Ok");
    }
}

Upvotes: 4

Related Questions