开发者

Using DataReader in VB.NET

开发者 https://www.devze.com 2023-03-18 12:31 出处:网络
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:

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 "'. Ple开发者_如何学JAVAase try another code.",vbOkOnly,"BookCode Exists")
   End If
 End While

Pleas help.


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)


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

0

精彩评论

暂无评论...
验证码 换一张
取 消