浏览量: 次
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
}
}
}
}
[声明]本网转载网络媒体稿件是为了传播更多的信息,此类稿件不代表本网观点,本网不承担此类稿件侵权行为的连带责任。故此,如果您发现本网站的内容侵犯了您的版权,请您的相关内容发至此邮箱【27535611@qq.com】,我们在确认后,会立即删除,保证您的版权。