views:

34

answers:

1

Does a connection made to the database get closed automatically when a call to the repeater's databind method is made?

here is the code snippet contained within a wrapper class method to the ent. lib.

public SqlDataReader RunQuery(string strQuery)
{
    Database db = DatabaseFactory.CreateDatabase();
    string sqlCommand = strQuery;
    DbCommand dbCommand = db.GetSqlStringCommand(sqlCommand);
    return (SqlDataReader)db.ExecuteReader(dbCommand,CommandBehavior.CloseConnection);
}

The presentation layer calls the wrapper class's method containing the above code like this

SQLwrap sr = new SQLwrap();
Repeater1.DataSource = sr.RunQuery("select ....");
Repeater1.DataBind();

is this the right way to do it?

I think I read somewhere long ago that the repeater.databind automatically closes the connection, but Im not sure about it now.

OK, if it does close the connection, then in the case where its not a repeater, how does one ensure that the connection has been closed?

Thanks.

A: 

Yes. All DB connections are closed after the command was invoked and the query has returned.

As you have created your DB object in a function, it goes out of scope and the connection will close after getting the results.

See this question for potential problems.

Oded
so my class that contains this function need not hold a dispose method nor implement the iDisposable interface ..is it?
If the Database class you are using implements IDisposable, best practice is to instantiate it with a using clause: `using (Database db = DatabaseFactory.CreateDatabase(){//code here}`
Oded