【问题标题】:Using DataReader in VB.NET在 VB.NET 中使用 DataReader
【发布时间】:2011-07-06 07:30:33
【问题描述】:

我使用以下代码收到错误消息There is an open data reader associated with this command which needs to be closed first

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

请帮忙。

【问题讨论】:

    标签: vb.net datareader sqlcommand


    【解决方案1】:

    不要重复使用 myCommand 变量。新建一个。

    myCommand 也应该在最后被处理(以及阅读器)。

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2015-08-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多