为什么我不能在一个程序中使用两个数据读取器?
你能解释一下为什么我不能在程序中使用两个数据读取器吗?
这是示例代码:
Private Sub Do_Execute()
Dim conx as SqlConnection
Dim cmd1 as SqlCommand
Dim cmd2 as SqlCommand
Dim drd1 as SqlDataReader
Dim drd2 as SqlDataReader
conx = new SqlConnection("connection string")
conx.Open()
cmd1 = new SqlCommand("SELECT * FROM Category" , conx)
drd1 = cmd1.ExecuteReader()
While (drd1.Read())
{
Reading Data From drd1
}
cmd2 = new SqlCommand("SELECT * FROM Stock" , conx)
drd2 = cmd2.ExecuteReader()
While (drd2.Read())
{
Reading Data From drd2
}
End Sub
当我执行该程序时,它会抛出异常消息: “已经有一个打开的 DataReader 与此命令关联,必须先关闭它!”
当我在初始化 drd2 之前关闭 drd1 时。有用。
为什么我不能使用上面的代码?请解释一下。提前致谢!
can you explain me why I can't use two datareader in on procedure?
Here is the sample code:
Private Sub Do_Execute()
Dim conx as SqlConnection
Dim cmd1 as SqlCommand
Dim cmd2 as SqlCommand
Dim drd1 as SqlDataReader
Dim drd2 as SqlDataReader
conx = new SqlConnection("connection string")
conx.Open()
cmd1 = new SqlCommand("SELECT * FROM Category" , conx)
drd1 = cmd1.ExecuteReader()
While (drd1.Read())
{
Reading Data From drd1
}
cmd2 = new SqlCommand("SELECT * FROM Stock" , conx)
drd2 = cmd2.ExecuteReader()
While (drd2.Read())
{
Reading Data From drd2
}
End Sub
When I execute that program, It throws to the exception message :
" There is already an open DataReader associates with this Command which must be closed first! "
When I closed drd1 before drd2 is initialized. It works.
Why I can't use like above code? Please explain me. Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是因为您实际上共享同一个连接。
您需要:
1) 为每个 SqlCommand 使用不同的连接,这是您以前必须执行此操作的原始方式
,或者
2) 按照 此处
It's because you're actually sharing the same connection.
You either need to:
1) use different connections for each SqlCommand, which was the original way you used to have to do this
or
2) use MARS (Multiple Active Result Sets) as described here
我以前没有尝试过,但应该是可能的。
阅读使用多个活动结果集并且,
的启用多个活动结果集
MSDN上 请注意,这是针对 SQL2005 及更高版本的。
摘自其中一篇文章:
I've not tried this before but it should be possible.
Read Using Multiple Active Result Sets and,
Enabling Multiple Active Result Sets on MSDN
Do note this is for SQL2005 and above.
Excerpt from one of the articles:
本文解释了问题所在,并且介绍如果您使用 SQL Server 的解决方案。该解决方案称为 MARS(即多个活动记录集),可在 SQL Server 2005 及更高版本中使用。
This article explains what the problem is, and introduces the solution if you are using SQL Server. The solution is called MARS, or Multiple Active Record Sets, and is available in SQL Server 2005 and later versions.