When to close connection?

G

Guest

I have a function that returns a SqlDataReader created by:

result = command.ExecuteReader(CommandBehavior.CloseConnection);

I then bind the result to a grid control:

myDataGrid.DataSource = sr;
myDataGrid.DataBind();

Do I need to explicitly close the DataReader (and thus the connection) after
the DataBind?

Thanks,
Bill
 
G

Guest

your function should use sqlreader.close. That should also take care of the
connection but I see your CommandBehavior is also taking care of the closing
the connection . In the calling client user sr = nothing.
 
G

Guest

If I do:

sr = null;

Won't this just flag the object for deletion until the garbage collection
actually destroys it? If I need to explicity close the reader, would it not
be better to call the Close method?

Anyhow, so I guess you are saying by this that I could also wait until the
Grid goes out of scope which will also set the sr to null.

Thanks
Bill
 
G

Guest

This is a sample

Try

DR = db.ExecuteReader(whatever)

While DR.Read

MsgBox(DR.Item(0))

End While

Catch ex As Exception

MsgBox(ex.Message)

Finally

If (Not DR Is Nothing) Then
DR.Close()
End If

End Try

look at the finally block and convert to c#.
 
C

Cor Ligthert [MVP]

Bill,

sr = null; or sr = nothing does in my opinion absolute nothing here, when
your page is sent back, everything that is not shared will be completely
released by the GC at the right time.

Clossing a connection is always needed of the connection pooling.
(Which you did as Chris already wrote)

I hope this gives an idea

Cor
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top