Do I need to Close DataReader in USING?

  • Thread starter Thread starter pvong
  • Start date Start date
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
 
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.
 
Back
Top