Wii close connection?

  • Thread starter Thread starter ad
  • Start date Start date
A

ad

I have a function call MyExecuteNonQuery(see bellow)
When I call it with some Sql command like:
MyExecuteNonQuery("Delete from myTable);
Will it close the conneciton which opened in MyExecuteNonQuery?







----------------------------------------------------------------------------
public int object MyExecuteNonQuery(string sSql)
{
string cnnStr="....";
SqlConnection cnn = new SqlConnection(cnnStr);
SqlCommand myCommand = new SqlCommand(sSql, cnn);
cnn.Open();
int iRV=myCommand.ExecuteNonQuery;
return iRV;

}
/*
 
Hi,

No, the connection will linger until such time as the garbage collection
process ie. Finalization etc. takes care of releasing the connection object.
You should explicitly close the connection, preferably by using a
try/finally block to ensure the connection is closed regardless of errors,
for C# I like the using statement to assist with this.

public int object MyExecuteNonQuery(string sSql)
{
string cnnStr="....";
int iRV;
using(SqlConnection cnn = new SqlConnection(cnnStr))
{
SqlCommand myCommand = new SqlCommand(sSql, cnn);
cnn.Open();
iRV=myCommand.ExecuteNonQuery;
} // At this point the cnn object will be disposed
return iRV;
}

Hope this helps
 
Hi,

No, ExecuteNonQuery does not close the connection automatically because it
is designed for catalog operations. You can do many catalog operations using
one connection. Use try - catch - finally statement instead :

try
{
cnn.Open();
myCommand.ExecuteNonQuery();
//
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (cnn.State != ConnectionState.Closed)
cnn.Close();
}
 
Please note that the Garbage Collection of the connection object in memory
and the closing of the Connection object (to the data source) are not the
same thing.

He should explicitly close the connection when he's done with it and then
the object can be destroyed based on memory management rules.
 
Back
Top