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

When to close a datareader and connection?

I have the following code below in a shared function within a self-created namespace. My question is; when and where should I close the datareader and connection. I am assuming that in this example if I close the datareader after 'End While' it will be too late as the the function will have already executed its return of X.

I am assuming the same is true if I close the datareader after the 'End If'

Or am I completely wrong? and if so... where do I close the datareader/connection.
If oDR.HasRows = True Then
                    While oDR.Read
                        Return X
                    End While
                    Return 0
                End If

Open in new window

1 Solution
You're correct, it would be too late.  Consider a variable to hold your return value, whether it is X or 0, and return it after the End If after you've closed the DataReader.

Also, if you're only going to return the one value, you don't need a while look.  If oDR.Read() then would accomplish the same.
instead of returning x in the loop assign it to a variable.

the code will then exit out the loop and this is where you close your connection / reader.

the code will then exit the if statment and its here where you should return the value
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

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