I’m wondering if this is a good way of doing data access, in terms of all the database objects being properly closed and disposed? For example:
Using conn As New SqlConnection(MyConnectionString)
Using cmd As New SqlCommand("some SQL here", conn)
... add parameters ...
conn.Open()
Using dr As SqlDataReader = cmd.ExecuteReader()
While dr.Read()
... do stuff ...
Wend
End Using
End Using
End Using
Is nesting Using like acceptable practice? If I exit the method at some point within the Read() loop, will the use of Using like this ensure all objects are cleaned up properly regardless?
Usingguarantees orderly disposal in an implicittry/finallyblock.Nested usings work in a similar fashion. If you exit a block of code, it will execute the
finallyblock, and properly dispose your objects.http://msdn.microsoft.com/en-US/library/htd05whh(v=VS.80).aspx