1

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 ?

3 Answers3

2

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*/ 
   }

}
Community
  • 1
  • 1
David
  • 72,686
  • 18
  • 132
  • 173
1

try using this:

using (SqlCeCommand cmd = new SqlCeCommand(cmdSQL))    
{
    cmd.Connection = (SqlCeConnection)this.SqlConnection;    
    var r = cmd.ExecuteScalar(CommandBehavior.CloseConnection);    
}
Kevin
  • 2,684
  • 6
  • 35
  • 64
  • Ok, but later in my code I do the same but I don't use ExecuteScalar. When I close the SqlCeCommand, does the connection close too ? – user1932593 Jan 04 '13 at 09:22
  • it works with all the Executes: http://msdn.microsoft.com/en-us/library/system.data.commandbehavior(v=vs.100).aspx You do not need to close it later on if you are using with your executions – Kevin Jan 15 '13 at 14:15
0

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.:)

Paritosh
  • 2,303
  • 2
  • 18
  • 24