zoukankan      html  css  js  c++  java
  • 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. }  
  • 相关阅读:
    Ceph纠删码编码机制
    Vmware error:无法获得 VMCI 驱动程序的版本: 句柄无效。
    Virtual Box 安装过程(卸载Vmware后)
    解决安卓SDK更新dl-ssl.google.com无法连接的方法
    《中文核心期刊要目总览(2014年版)》——计算机、自动化类
    2014中国科技核心期刊(中国科技论文统计源期刊)名录——计算机类
    计算机专业方面的期刊
    Office 中的各种小tips(更新中)
    博客园添加背景音乐
    jmeter定时器
  • 原文地址:https://www.cnblogs.com/lykbk/p/ertertertjerit34534u54954i.html
Copyright © 2011-2022 走看看