可使用以下两种方法确保在不用联接时关闭连接
1、使用 try...catch...finally 语句块
try
{
con.open();
//open the connection
//do some useful
}
catch(exception ex)
{
// do some about exception
}
finally
{
con.close();
//close the con
}
2、使用using
using(SqlConnection con =new SqlConnection)
{
con.open();
// do some useful
con.close();
}
两种联合使用
try
{
using(SqlConnection con =new SqlConnection)
{
con.open();
// do some useful
con.close();
}
}
catch(exception ex)
{
//do some about exception
}