Should I be using SqlDataReader inside a quot;usingquot; statement?(我应该在“使用中使用 SqlDataReader 吗?陈述?)
问题描述
以下两个例子哪个是正确的?(或者哪个更好,我应该使用哪个)
Which of the following two examples are correct? (Or which one is better and should I use)
在 MSDN 中我发现了这个:
In the MSDN I found this:
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();
}
}
但是,一些用户建议以这种方式查看其他页面:
However looking other pages some users suggest to do it this way:
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
语句,或者它们会自动处理SqlConnection
using
代码块的结尾.
So, the question is: should I use the using
statement also in the SqlCommand
and in the SqlDataReader
or they are automatically disposed at the end of the SqlConnection
using
code block.
推荐答案
第二个选项意味着你的reader
在创建后如果出现异常会关闭,所以首选.
The second option means your reader
will be closed in the event of an exception after it has been created, so it is preferred.
它被编译器有效地转换为:
It is effectively transformed by the compiler to:
SqlDataReader reader = command.ExecuteReader();
try
{
....
}
finally
{
if (reader != null)
((IDisposable)reader).Dispose();
}
有关详细信息,请参阅 MSDN.
See MSDN for more info.
这篇关于我应该在“使用"中使用 SqlDataReader 吗?陈述?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我应该在“使用"中使用 SqlDataReader 吗?陈述?


- 在 LINQ to SQL 中使用 contains() 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- 使用 rss + c# 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01