Stats

An Easy Way To Query a Database

The following samples should take advantage of using statements and furthermore built in features of the ADO.NET framework. Furthermore, if you open a connection, make sure you open it at the latest time possible and close it as soon as possible.Edit: While I was originally not trying to...

The following samples should take advantage of using statements and furthermore built in features of the ADO.NET framework. Furthermore, if you open a connection, make sure you open it at the latest time possible and close it as soon as possible.

Edit: While I was originally not trying to change too much of the original content, I might as well to incorporate all of the suggestions posted below. As woric and I noticed, the exception handling is generally not a good idea, so it can be removed and handled at a higher level. Though, the using statement should be used to close the connection, so the try/finally isn't necessary. Then, as Fzelle pointed out, the SqlDataAdapter can be passed the connection string and query to simplify that method.

Hi Andrew,I would probably agree. The general idea I put in my comment is to try avoiding any potential exception raising, because exception handling is relatively "expensive" procedure. Also, Connection object in addition to Open/Closed state has another state (StateConnecting); not sure how system will react on any attempt to perform operations or to close the connection in that state, though in synchronous mode this probably will never happen. Best regards, Alex

I already voted 5 for this solution and would like just to point to one possible minor improvement: it could be a good idea to check if connection state, i.e. if it is closed or open, like if(con.State == ConnectionState.Open), etc. in order to avoid unnecessary exception raising/handling.

Checking the state is unnecessary. The calling "Close" twice on a connection doesn't throw an exception. Plus, there are only two ways to close the connection. One is the normal path without exceptions where the "Close" immediately after the ExecuteNonQuery (which even this could be omitted if you favored leaving it up to the dispose of the SqlConnection). The other way is the exceptional, which is where the dispose will correctly close the connection for you.