Test sql connection without throwing exception

怎甘沉沦 提交于 2020-01-02 02:19:05

问题


To test if i can connect to my database, I execute the following code :

using (SqlConnection connection = new SqlConnection(myConnectionString))
{
   try
   {
      connection.Open();
      canConnect = true;
   }
   catch (SqlException) { }
}

This works except it throws an exception if the connection failed. Is there any other way to test a Sql connection that doesn't throw an exception ?

Edit : To add precision, i'm asking if there is a simple method that does that without having to open the connection and catch exceptions that can occur


回答1:


When attempting to open a connection, there is no way to avoid the exception if the connection can't be opened. It can be hidden away in a function somewhere, but you're going to get the exception, no matter what.

It was designed like this because generally you expect to be able to connect to the database. A failed connection is the exception.

That being said, you can test the current connection state at any time by checking the State property.




回答2:


write an extension like so:

public static class Extension{
 public static bool CanOpen(this SqlConnection connection){
   try{
    if(connection == null){ return false; }

    connection.Open();
    var canOpen = connection.State == ConnectionState.Open;
    connection.close();
    return canOpen;
 }
 catch{
  return false;
 }
}

Then you can consume it like:

 using(var connection = new SqlConnection(myConnectionString)){
      if(connection.CanOpen()){
       // NOTE: The connection is not open at this point...
       // You can either open it here or not close it in the extension method...
       // I prefer opening the connection explicitly here...
     }
}

HTH.




回答3:


If it throws an an exception and you handle it in your catch block you already know the connection failed. I think you answered your own question.




回答4:


I think the real answer here is ping.

string data = "ismyserverpingable";
byte[] buffer = Encoding.ASCII.GetBytes (data);
int timeout = 120;
PingReply reply = pingSender.Send ("google.com", timeout, buffer, options);
if (reply.Status == IPStatus.Success)
{
}

Unless you are explicitly checking to see if a sql connection is possible 9/10 you should know if something is a sql server. This would save you that nasty memory usage of an exception which is what i am betting you are really after.




回答5:


You could always use the ConnectionStringBuilder class and check for the existence of each piece that is required by a connection string before attempting to open it.

If the connection string is correct, but the database server you're connecting to is down, you're still going to get an excepton. Kind of pointless to check the quality of the string if the endpoint you're connecting to can potentially be offline.




回答6:


You can not avoid exception coming while connecting database but have some function which handle this very well. I am using this function which return true if connection exist.

    public static bool IsSQLConnectionAvailable()
    {
        SqlConnection _objConn = new SqlConnection();

        try
        {
            _objConn.ConnectionString = ConfigurationManager.ConnectionStrings["DefaultSQLConnectionString"].ConnectionString;
            _objConn.Open();
        }
        catch
        {
            return false;
        }
        finally
        {
            if (_objConn.State == ConnectionState.Open)
                _objConn.Close();
        }

        return true;
    }


来源:https://stackoverflow.com/questions/2601497/test-sql-connection-without-throwing-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!