Data connection question

  • Thread starter Thread starter William Gower
  • Start date Start date
W

William Gower

In Java I would open a connection to the database on each page and close it
before leaving the page for connection pooling purposes. Do I do the same
with ASP.Net?
 
No. ADO.NET works in two modes, connected and disconnected mode. You use
connected mode when you use a datareader or when you call one of the
executexx methods of the command object. You'll open the connection, do
whatever with it, for instance fire teh query and walk through your
datareader, then close it. A user may be on your page for 10
minutes...you'll only keep your connection open to perform the task at hand
or grab some data.
myDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);

while(myDataReader.Read()){
//do something.
}
If you don't use the CommandBehavior enum, manually close the connection
You technically can leave a connection open but it's Very bad practice and
antithetical to the whole architecture of ADO.NET. ADO.NET give you a lot
of features, but the disconnected model has some overhead. By leaving your
connections open, you get the worst of all worlds..

On the other hand, you can use the disconnected method and the dataadapter
automatically opens and closes the connections for you. YOu can override
this, but either way you should close it ASAP when your query is over

dataAdapter.Fill(myDataSet, "tableName");
//Now the connection is close

The long and short is that the time a user views a page has no relation to
how long the connection should be open or closed.

HTH,

Bill
 
Back
Top