DataReader not closed when Connection is closed, consequences?

Garry - picture Garry - · May 31, 2011 · Viewed 8.5k times · Source

for example i have this code :

Sub Month()
    Dim Conn As New Data.OracleClient.OracleConnection
    Conn.Open()
    Try

        Dim Cmd As New Data.OracleClient.OracleCommand
        With Cmd
            .Connection = Conn
            .CommandType = Data.CommandType.Text
            .CommandText = "SELECT * FROM MONTH"
        End With
        Dim datareader As Data.OracleClient.OracleDataReader = Cmd.ExecuteReader
        While datareader.Read
            Response.Write(datareader(0))
        End While
    Catch ex As Exception
        Throw ex
    Finally
        Conn.Close()
    End Try
End Sub

What will happen to the datareader when the Connection is closed ( Conn.close)

Will the Cursor that is used by the datareader be freed ? or will it stay open ?

If the cursor that is used by the datareader is still open , when will it be automatically closed ? or should i just closed it manually ?

Will it cause the dreaded "ORA-01000: maximum open cursors exceeded" ?

thanks in advance

Answer

Chris Dunaway picture Chris Dunaway · May 31, 2011

You should create the objects in a using block so they are properly disposed:

Using Conn As New Data.SqlClient.SqlConnection
    Conn.Open()

    Dim Cmd As New Data.SqlClient.SqlCommand
    With Cmd
        .Connection = Conn
        .CommandType = Data.CommandType.Text
        .CommandText = "SELECT * FROM MONTH"
    End With

    Using datareader As Data.SqlClient.SqlDataReader = Cmd.ExecuteReader()
        While datareader.Read()
            Response.Write(datareader(0))
        End While
    End Using
End Using

There is no need to call Close on either the connection or the datareader.