How to check connection to database?
t-sql, sql server 2008
My application must check connection status to database every 5 seconds. I did it as code below:
static bool Check()
{
using (SqlConnection conn = new SqlConnection("Server=WS-01\\ex1; User id=Admin; pwd=123; database=database"))
开发者_如何学C {
try
{
conn.Open();
if (conn.State != ConnectionState.Open)
return false;
else
return true;
}
catch
{
return false;
}
finally
{
try
{
conn.Close();
}
catch
{
}
}
}
}
static void Main(string[] args)
{
Console.WriteLine(Check());
Console.ReadKey();
}
}
Is there any easier way to do that ? I don't familiar with some specific t-sql instructions ...
You can remove the finally - you do not need to manually close the connection when you have a using()
wrapping your connection object.
Also, the connection timeout will likely be longer than 5 seconds, so you may end up with a queue of failures.
精彩评论