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. }  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值