主营业务:网站制作 网站优化 小程序制作 石家庄网站制作网站建设有限公司欢迎您!
石家庄闪云网络科技有限公司
客服热线15383239821
如何让自己的网站更有质量?

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

发布时间:2011/2/19 6:28:58

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

 

using System;
using System.Data.SqlClient;

namespace Magci.Test.DataAccess
{
   
class Program
   
{
      
static void Main(string[] args)
      
{
          
string source = @"server=.\sqlexpress; integrated security=SSPI; database=msdb";
         
SqlConnection conn = null;
         
//使用try块处理
         
try
          
{
              
conn = new SqlConnection(source);
             
conn.Open();
             
//Do something
         
}
         
catch (Exception e)
        
{
             
//Do something with the exception
          
}
          
finally
          
{
              
conn.Close();
          
}

 
         
//使用using块处理
          
using (conn = new SqlConnection(source))
          
{
               
conn.Open();
               
//Do something
          
}
 
 
           
//两种组合方式
          
try
          
{
              
using (conn = new SqlConnection(source))
             
{
                  
conn.Open();
                  
//Do something
                  
conn.Close();
             
}
          
}
          
catch (Exception e)
          
{
             
//Do something with the exception
         
}
      
}
   
}
}

上一篇: C#中split用法
下一篇: cstr用法

相关新闻推荐

在线客服 : 服务热线:15383239821 电子邮箱: 27535611@qq.com

公司地址:石家庄市新华区九中街江西大厦4062

备案号:冀ICP备2022000585号-4