0

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

4 Answers 4

4
using (var connection = new SqlConnection("connectionString"))
{
    try
    {
        connection.Open();
        Console.WriteLine("Connection Ok");
    }
    catch (SqlException)
    {
        Console.WriteLine("Connection Not Ok");
    }
}
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

1

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.

Comments

0

Check the state of the connection.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.