打开 SqlDataReader 时有什么方法可以避免嵌套使用?
没什么大不了的,但为了整洁起见,有什么方法可以“创建并打开”SqlConnection
吗?
我天真地编写了这段代码:
using (var strConnection = new SqlConnection(sourceConnection))
using (var strCommand = new SqlCommand(query, strConnection))
using (var reader = strCommand.ExecuteReader())
{
...
}
这当然会在第 3 行失败,因为连接未打开。
有没有一种巧妙的方法来避免打开连接引入的嵌套?
using (var strConnection = new SqlConnection(sourceConnection))
{
strConnection.Open();
using (var strCommand = new SqlCommand(query, strConnection))
using (var reader = strCommand.ExecuteReader())
{
...
}
}
Not a big deal but for neatness sake is there any way to "create and open" a SqlConnection
?
I naively wrote this code:
using (var strConnection = new SqlConnection(sourceConnection))
using (var strCommand = new SqlCommand(query, strConnection))
using (var reader = strCommand.ExecuteReader())
{
...
}
Which of course fails on line 3 because the connection isn't open.
Is there a neat way to avoid that nesting that opening the connection introduces?
using (var strConnection = new SqlConnection(sourceConnection))
{
strConnection.Open();
using (var strCommand = new SqlCommand(query, strConnection))
using (var reader = strCommand.ExecuteReader())
{
...
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好问题,我的想法是
SqlConnection
的扩展方法。检查一下:
用法:
Good question, my idea is an Extension-Method for
SqlConnection
.Check this:
Usage:
类似的事情怎么样:
在你的代码中
What about something like that:
and in your code