Avatar of rutledgj
rutledgj

asked on 

vb.net proper way to use Using statement with data readers

I've been trying to convert a database class to using the Using statement to help eliminate possible memory leaks. I'm a bit unsure about how to do this with datareaders since you can't close the connection and still read the reader.  Can someone tell me if the following is correct? Since the return is within the using blocks, what happens to the connections and objects? Is there a better way?

Friend Function ExecuteDataReader(ByVal ConnString As String, ByVal SqlQuery As String, ByVal CmdType As System.Data.CommandType) As MySqlDataReader

                Try
                    Using SqlConn As New MySqlConnection(ConnString)
                        Using SqlCmd As New MySqlCommand(SqlQuery, SqlConn)
                            SqlCmd.CommandType = CmdType
                            SqlConn.Open()
                            Using drReader As MySqlDataReader = SqlCmd.ExecuteReader()
                                 Return (drReader)
                            End Using
                        End Using
                    End Using
                Catch ex As Exception
                    Throw New Exception("Error in MySqlDataBaseOperations.ExecuteDataReader with error: " & ex.ToString)
                End Try
            End Function
Visual Basic.NET

Avatar of undefined
Last Comment
Ironhoofs
ASKER CERTIFIED SOLUTION
Avatar of sindhuxyz
sindhuxyz

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of Ironhoofs
Ironhoofs
Flag of Netherlands image

Use Try..Catch.. Finally:


The code in the finally block gets  run after try / catch. Declare all objects beforehand without "Using" and clean up all objects after your code finished.
Visual Basic.NET
Visual Basic.NET

Visual Basic .NET (VB.NET) is an object-oriented programming language implemented on the .NET framework, but also supported on other platforms such as Mono and Silverlight. Microsoft launched VB.NET as the successor to the Visual Basic language. Though it is similar in syntax to Visual Basic pre-2002, it is not the same technology,

96K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo