简体   繁体   中英

How can I identify all connection related exception types in an SqlException?

I am writing a VB.net winforms application which connects to Sql server 2008. (C# answers also accepted)

I am trying to differentiate between any SqlExceptions related to the connection to the database and other SQL specific errors (such as incorrect syntax etc.)

I am using a try/catch around the connection like so:

Try
   //code to open the connection/access the DB/etc.
Catch ex As SqlException When ex.Number=???
   //Do stuff
End Try

I am presuming that checking the error code is the correct way to go. My issue is that there are a number of different error codes (i'm not sure how many) relating to the connection to the database. For example:

121 = Timeout (could be caused by disconnecting from the network).

53 = Could not connect (again, could be caused by not being connected to the network).

1326 = You are connected to the physical server machine but the Sql Server is not running.

And I am sure that there are many, many more. Do I have to check for each of these individually or is there a better way? If I have to check for them individually, is there a list of the connection related ones anywhere that I can refer to?

As @jdweng Suggested in comments, I added a try/catch block around just the query. So that if an exception occurred, it couldn't be anything else but connection related.

So simple! Thanks again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM