Validate SQL Server Connection
How i could check if i have connection to an SQL Server with the Connection Str开发者_如何转开发ing known in C#?
using (var connection = new SqlConnection("connectionString"))
{
try
{
connection.Open();
Console.WriteLine("Connection Ok");
}
catch (SqlException)
{
Console.WriteLine("Connection Not Ok");
}
}
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
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.
Check the state of the connection.
if (conexion.State == ConnectionState.Closed)
{
conexion.Open();
}
精彩评论