C#中释放数据库连接资源

1.确保释放数据库连接资源的两种方式如下:
   a.使用try...catch...finally语句块,在finally块中关闭连接;
   b.使用using语句块,无论如何退出,都会自动关闭连接;
2.最好的方法是组合使用以上两种方式。
   using System;   

  1. using System.Data.SqlClient;   
  2.   
  3. namespace Magci.Test.DataAccess   
  4. {   
  5.     class Program   
  6.      {   
  7.         static void Main(string[] args)   
  8.          {   
  9.             string source = @"server=.sqlexpress; integrated security=SSPI; database=msdb";   
  10.              SqlConnection conn = null;   
  11.             //使用try块处理   
  12.             try  
  13.              {   
  14.                  conn = new SqlConnection(source);   
  15.                  conn.Open();   
  16.                 //Do something   
  17.              }   
  18.             catch (Exception e)   
  19.              {   
  20.                 //Do something with the exception   
  21.              }   
  22.             finally  
  23.              {   
  24.                  conn.Close();   
  25.              }   
  26.   
  27.             //使用using块处理   
  28.             using (conn = new SqlConnection(source))   
  29.              {   
  30.                  conn.Open();   
  31.                 //Do something   
  32.              }   
  33.   
  34.             //两种组合方式   
  35.             try  
  36.              {   
  37.                 using (conn = new SqlConnection(source))   
  38.                  {   
  39.                      conn.Open();   
  40.                     //Do something   
  41.                      conn.Close();   
  42.                  }   
  43.              }   
  44.             catch (Exception e)   
  45.              {   
  46.                 //Do something with the exception   
  47.              }   
  48.          }   
  49.      }   
  50. }  
原文地址:https://www.cnblogs.com/lykbk/p/ertertertjerit34534u54954i.html