Click here to Skip to main content
15,891,033 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more: , +
As per the Subject line, a very quick question ...

I have code similar to this in various places in my program :

VB
If mySqlConn.State = ConnectionState.Closed Then mySqlConn.Open()
            Using mySqlRdr As SqlCeDataReader = mySqlCmd.ExecuteReader()
                mySqlCmd.ExecuteNonQuery()
                mySqlConn.Close()
                Me.Hide()
                MasterForm.Show()
            End Using


I've just noticed that although I always Open mySqlConn ... in some places I close MySqlConn & in some places I close mySqlRdr ... which should I be doing, or should I be doing both ?!?
Posted
Comments
[no name] 20-Jul-12 14:28pm    
For objects that implement IDisposable you should be wrapping their usage in using blocks like you are for your reader.
Gary Heath 20-Jul-12 14:36pm    
Some of them are in Using blocks, some aren't, I need to go through and standardise them ... thanks

1 solution

In the code above, you close both your Connection (explicitly, via teh Close method) and the Readewr (implitly, via the using block which does a Close and Dispose).

What you should be doing is closing both and (preferably) Disposing both, since they are scarce resources and should not be hogged!
Personally, I use a using block on the Connection, Command and Reader to be sure.
 
Share this answer
 
Comments
Gary Heath 20-Jul-12 14:37pm    
Yes, I just mentioned in the comment above that some of them are, I need to standardise them ... does this mean that if they are in Using blocks, I can omit the Close, or is best practice to close the Connection anyway ?
lewax00 20-Jul-12 14:42pm    
Generally, Close is just a call to Dispose anyways (assuming it derives from the Stream class, or uses a similar design). Calling it again doesn't hurt, but when the object is disposed it should release all resources, so you shouldn't need to. The best practice is really just to wrap it in a using block, and let the framework/language do it's job.
Gary Heath 20-Jul-12 14:54pm    
Everything's wrapped in Using blocks now, thanks everybody ... and yes, lewax00, that makes a lot of sense !!!
OriginalGriff 20-Jul-12 15:02pm    
That is certainly not the case for SqlConnections - Close and Dispose are different animals. Forms are the same, and I would guess that MySqlConnections are as well.
http://blogs.msdn.com/b/kimhamil/archive/2008/03/15/the-often-non-difference-between-close-and-dispose.aspx
lewax00 20-Jul-12 16:05pm    
MSDN disagrees, "Close and Dispose are functionally equivalent", from http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.close.aspx#Y0

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900