user1932593
user1932593

Reputation: 15

Closing database connections

To close my database I use this : SqlConnection.Close(); But my application is stuck in this method...

Each time I access the Database I do this :

string cmdSQL = "select min(shortAddress) from FreeShortAddress";

using (SqlCeCommand cmd = new SqlCeCommand(cmdSQL))    
{
    cmd.Connection = (SqlCeConnection)this.SqlConnection;    
    var r = cmd.ExecuteScalar();    
}

Is it the right way ?How can you see which connection (on which table) is blocked ?

Thank you.

[Edit]Do you know a command to force closing all connections without being stuck ?

Upvotes: 1

Views: 265

Answers (3)

Kevin
Kevin

Reputation: 2688

try using this:

using (SqlCeCommand cmd = new SqlCeCommand(cmdSQL))    
{
    cmd.Connection = (SqlCeConnection)this.SqlConnection;    
    var r = cmd.ExecuteScalar(CommandBehavior.CloseConnection);    
}

Upvotes: 1

Paritosh
Paritosh

Reputation: 2379

This is really a way to go while closing connection, I really used it everywhere to avoid clutter the code by using try catch statement, BTW you can use yield keyword in your version. but not with try catch.:)

Upvotes: 0

David
David

Reputation: 73604

The general pattern I use when opening and closing connections is like this: (taken from an older answer of mine on a question about the using statement.) This patterns closes the connection automatically when it is supposed to be closed. (When exiting the using statement)

using (SqlConnection connection = new SqlConnection(connectionString)) 
{    
  int employeeID = findEmployeeID();    
  try    
  {

            connection.Open();
            SqlCommand command = new SqlCommand("UpdateEmployeeTable", connection);
            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.Add(new SqlParameter("@EmployeeID", employeeID));
            command.CommandTimeout = 5;

            command.ExecuteNonQuery();    
   } 
   catch (Exception) 
   { 
      /*Handle error*/ 
   }

}

Upvotes: 2

Related Questions