Do I need to Close DataReader in USING?

P

pvong

Newbie doing this in VB.NET

I have a simple "USING" to create my DataReader. I end it with END USING
and I know this will close the connection. Will this close my dr also or do
I need to add dr.close() ever time?
Thanks!
Phil



Using cn As IDbConnection = New
SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)Dim
cmd As New SqlCommand("SELECT Statement", cn)
cn.Open()
Dim dr As SqlDataReader = cmd.ExecuteReader(CommandBehavior.SingleRow)
dr.Read()

Reading my stuff here.

[do i need a dr.close() here?]

End Using
 
G

Göran Andersson

pvong said:
Newbie doing this in VB.NET

I have a simple "USING" to create my DataReader. I end it with END USING
and I know this will close the connection. Will this close my dr also or do
I need to add dr.close() ever time?
Thanks!
Phil



Using cn As IDbConnection = New
SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)Dim
cmd As New SqlCommand("SELECT Statement", cn)
cn.Open()
Dim dr As SqlDataReader = cmd.ExecuteReader(CommandBehavior.SingleRow)
dr.Read()

Reading my stuff here.

[do i need a dr.close() here?]

End Using

You should have a Using for the reader also:

Using cn As New
SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
Dim cmd As New SqlCommand("SELECT Statement", cn)
cn.Open()
Using dr As SqlDataReader = cmd.ExecuteReader(CommandBehavior.SingleRow)
While dr.Read()
' Reading my stuff here.
End While
End Using
End Using

This ensures that both the reader and the connections are closed
properly, even if there is an exception in the code reading the data.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,931
Messages
2,570,085
Members
46,536
Latest member
keelop

Latest Threads

Top