Keo*_*oki 25 .net c# ado.net sqlconnection
以下哪两个例子是正确的?(或哪一个更好,我应该使用)
在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();
}
}
Run Code Online (Sandbox Code Playgroud)
但是,查看其他页面,一些用户建议这样做:
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]));
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
所以,问题是:我是否应该using在SqlCommand和中使用该语句,SqlDataReader或者它们会自动放置在SqlConnection using代码块的末尾.
Dan*_*ley 35
第二个选项意味着您reader将在创建异常后关闭,因此首选.
它被编译器有效地转换为:
SqlDataReader reader = command.ExecuteReader();
try
{
....
}
finally
{
if (reader != null)
((IDisposable)reader).Dispose();
}
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请参阅MSDN.
Bin*_*x1n 16
你实际上可以一起列出使用,一个la:
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]));
}
}
}
}
Run Code Online (Sandbox Code Playgroud)