If you think about this at a really high level, there is no good asnwer to checking state of connection prior to executing statement.
Primary reason is you can check the state of the connection and it is 100% good and then 1 millisecond later it can drop.
So in the end you will still need to have code to handle exceptions that occur when the connection goes bad, even if you check the connection prior to running the sql statement.
To test a connection you could write a simple function like so:
bool FConnectionIsGood(SqlConnection conn) { using (SqlCommand cmd = conn.GetCommand()) { cmd.CommandText = "select 1"; cmd.CommandType = CommandType.Text; try { cmd.ExecuteScalar(); } catch (Exception) { return false; } } return true; }
But what is the point of having this function because as soon as this function returns 1 millisecond later the connection can drop. Also every time you use a connection you do some extra wasteful work checking the connection and do this 1000s of times when you don't need to do it for the 1 time that it might save using a bad connection.
Sort of the same argument for using exception handling versus checking error codes over and over. It's more efficient to just execute the code without any checks and in the exceptional case let the exception handling code do it's work.
|