以下兩個例子中的哪一個是正確的? (或者哪一個更好,我應該使用)我應該在「using」語句中使用SqlDataReader嗎?
在MSDN,我發現這一點:
private static void ReadOrderData(string connectionString)
{
string queryString = "SELECT OrderID, CustomerID FROM dbo.Orders;"
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
// Call Read before accessing data.
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}", reader[0], reader[1]));
}
// Call Close when done reading.
reader.Close();
}
}
但是看其他網頁上有一些用戶建議做這種方式:
private static void ReadOrderData(string connectionString)
{
string queryString = "SELECT OrderID, CustomerID FROM dbo.Orders;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand(queryString, connection))
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
// Call Read before accessing data.
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}", reader[0], reader[1]));
}
}
}
}
}
所以,問題是:我是否也應該在SqlCommand
和SqlDataReader
中使用using
聲明,或者它們自動置於代碼塊的末尾。
可能重複[是否需要手動關閉和處置SqlDataReader?](http://stackoverflow.com/questions/744051/is-it-necessary-to-manually-close-and-dispose-of- sqldatareader) – 2015-10-20 12:03:00
也有關:[將在DataReader附近放置一個「using」語句關閉它?](http://stackoverflow.com/q/2157276/456814)。 – 2015-10-20 12:03:26