• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 215
  • Last Modified:

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
0
rutledgj
Asked:
rutledgj
1 Solution
 
sindhuxyzCommented:
You have used correct way; and YES dispose method will be called even if you have returned from Using statement

using statement is the same as:
try{
// do something with the connection
// maybe return
}finally{
mySQLconn.Dispose();
}
0
 
IronhoofsCommented:
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.
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now