在 VB.NET 中使用 DataReader

发布于 2024-11-19 04:21:46 字数 714 浏览 4 评论 0原文

我收到错误消息有一个与此命令关联的开放数据读取器,需要首先关闭,使用以下代码:

myCommand = New SqlCommand("SELECT BookCode FROM tblBook",myConnection)
 myReader = myCommand.ExceuteReader
 While myReader.Read
   If myReader(0).ToString <> txtBookCode.Text Then
      myCommand = New SqlCommand("INSERT INTO tblBook VALUES(@BookCode, @BookTitle)",myConnection)
      myCommand.Parameters.AddWithValue("@BookCode", txtBookCode.Text)
      myCommand.Parameters.AddWithValue("@BookTitle", txtBookTitle.Text)
      myCommand.ExecuteNonQuery()
   Else
      MsgBox("There is already a book name '"& txtTitle.Text "'. Please try another code.",vbOkOnly,"BookCode Exists")
   End If
 End While

请帮助。

I got the error message There is an open data reader associated with this command which needs to be closed first by using the following code:

myCommand = New SqlCommand("SELECT BookCode FROM tblBook",myConnection)
 myReader = myCommand.ExceuteReader
 While myReader.Read
   If myReader(0).ToString <> txtBookCode.Text Then
      myCommand = New SqlCommand("INSERT INTO tblBook VALUES(@BookCode, @BookTitle)",myConnection)
      myCommand.Parameters.AddWithValue("@BookCode", txtBookCode.Text)
      myCommand.Parameters.AddWithValue("@BookTitle", txtBookTitle.Text)
      myCommand.ExecuteNonQuery()
   Else
      MsgBox("There is already a book name '"& txtTitle.Text "'. Please try another code.",vbOkOnly,"BookCode Exists")
   End If
 End While

Pleas help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

请帮我爱他 2024-11-26 04:21:46

不要重复使用 myCommand 变量。创建新的。

myCommand 也应该最终被处理(以及 reader)。

异常的真正原因更有可能是您尝试同时在一个连接上运行两个命令。
首先从阅读器读取您需要的所有数据,然后进行所有插入。不是同时两个(我假设你不想创建两个连接。那会很糟糕)

Don't reuse myCommand variable. Create new one.

myCommand should be disposed in the end too (as well as reader).

Real reason of exception is more likely that you're trying to run two command on one connection at the same time.
First read all data you need from reader and THEN do all inserts. Not both at once (i assume you don't want to create two connections. That would suck)

依 靠 2024-11-26 04:21:46

看起来您正尝试在第一行代码和 WHILE 循环内多次使用一个变量 myCommand 。
最好再声明一个 AdoCommand 变量以在 LOOP 中使用它

looks like you're trying to use one variable myCommand more than once - in the first line of code and within a WHILE loop.
it's better to declare one more AdoCommand variable to use it in LOOP

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文