Introducing Radical.sh

Forget Code launches a powerful code generator for building API's

Check connection in C#



After making a connection with connection object,
it is important for a programmer to validate the connection whether it is working or not.
Here, ForgetCode suggests a simple code to check for.

Assume that the connection object con1 was created already.

  1.  
  2. public int checkConnection()
  3. {
  4. // Try block with Executable commands
  5. try
  6. {
  7. //Opening Connection
  8. con1.Open();
  9. return 1;
  10. }
  11.  
  12. // Catch block -For tracking unsuccessful cases
  13. catch
  14. {
  15. return 0;
  16. }
  17.  
  18. // Closing connection in 'must be Executed block'
  19. finally
  20. {
  21. con1.Close();
  22. }
  23.  
  24. }
  25.  


If the connection is opened successfully, 1 will be returned and the connection will be immediately closed by the finally block.

..