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 吗?陈述?


基础教程推荐
- rabbitmq 的 REST API 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 将 XML 转换为通用列表 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01