服務(wù)熱線
153 8323 9821
1.確保釋放數(shù)據(jù)庫連接資源的兩種方式如下:
a.使用try...catch...finally語句塊,在finally塊中關(guān)閉連接;
b.使用using語句塊,無論如何退出,都會自動關(guān)閉連接;
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用法