asp.net 使用using代码块 摘

"ado.net 2.0 技术内幕

强烈建议在Using代码块内所有可能的位置创建短期生存对象。

Using 块确保及时在Using块内波发生未处理异常时也会在该代码块的末尾调用 Dispose 方法。

 

例子:

  
    
string strConn, strSQL;
strconn
= @" Data Source=.\SQLExpress; " + " Initial Catalog = Northwind;Integrated Security=True; " ;
strSQL
= " SELECT CustomerID, CompanyName FROM Customers " ;
Using (SqlConnection cn
= new SqlConnection(strConn)) {
Try {
cn.Open();
}
Catch (SqlException ex) {
Consolse.WriteLine(
" Connect attempt failed " );
Consolse.WriteLine(
" {0} " , ex.Message);
return ;
}

Using (SqlCommand cmd
= new SqlCommand(strSQL, cn) {
try {
using (SqlDataReader rdr = cmd.ExecuteReader()) {
while (rdr.Read())
Console.WriteLine(rdr[
" CompanyName " ]);
rdr.Close();
}
}
catch (SqlException ex) {
Console.WriteLine(
" Query failed " );
Console.WriteLine(
" {0} " , ex.Message);
return ;
}
}
cn.Close();
}
"

你可能感兴趣的:(asp.net)