"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();
}
"

相关文章:

  • 2022-12-23
  • 2021-06-11
  • 2022-01-15
  • 2022-02-09
  • 2022-01-31
  • 2021-11-01
  • 2021-09-14
  • 2021-09-15
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-01-08
  • 2021-07-23
  • 2021-10-23
  • 2021-05-21
  • 2021-06-09
相关资源
相似解决方案