0

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.

2 Answers 2

2

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)

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.