1

我在编码中遇到此错误,您能告诉我可能出了什么问题吗?以及如何纠正它

已经有一个打开的 DataReader 与此 Connection 关联,必须先关闭它。在这个 sub 中,我在 if 部分中检索数据,在 else 部分中我正在插入数据。如果一个条件不满足。所以在其他部分我得到了上述错误

代码是:

 Dim con As MySql.Data.MySqlClient.MySqlConnection = New MySqlClient.MySqlConnection("server=localhost;user=root;database=zzz;port=3306;password;")
    con.Open()
    Dim cmd As MySqlClient.MySqlCommand
    Dim dr As MySqlClient.MySqlDataReader
    cmd = con.CreateCommand()
    cmd.CommandText = "select sino FROM customers WHERE sino  =('" + serialno.Text + "')"
    cmd.ExecuteNonQuery()
    dr = cmd.ExecuteReader()
    If dr.HasRows = True Then
        MsgBox("number already exists")
        dr.Close()

    ElseIf dr.HasRows = False Then

        Dim sqlc As String
        sqlc = "insert into customers values('" + serialno.Text + "','" + custname.Text + "','" + address.Text + "','" + phno.Text + "','" + eid.Text + "','" + event_type.Text + " ')"
        Dim command As MySqlClient.MySqlCommand = New MySqlClient.MySqlCommand(sqlc, con)
        command.ExecuteNonQuery()
        MessageBox.Show(sqlc)
        con.Close()
    End If
4

2 回答 2

2

DataReader 只能与一个打开的连接相关联。完成 DataReader 后,请确保在再次使用之前关闭()它。

来自 MSDN: http: //msdn.microsoft.com/en-us/library/haa3afyz (v=vs.80).aspx

于 2013-03-22T15:09:23.413 回答
0

1) 删除 cmd.ExecuteNonQuery()。紧随其后的 ExecuteReader 是您需要的唯一执行。2)您必须为您的插入命令使用不同的连接对象或关闭以前的阅读器。当您循环连接到它的阅读器时,您不能重复使用相同的连接对象。所以试试这个:

Dim con As MySql.Data.MySqlClient.MySqlConnection = New MySqlClient.MySqlConnection("server=localhost;user=root;database=zzz;port=3306;password;")
con.Open()
Dim cmd As MySqlClient.MySqlCommand
Dim dr As MySqlClient.MySqlDataReader
cmd = con.CreateCommand()
cmd.CommandText = "select sino FROM customers WHERE sino  =('" + serialno.Text + "')"
dr = cmd.ExecuteReader()
If dr.Read = False Then
  'we have no existing record
  dr.Close()  'close reader first
   Dim sqlc As String
    sqlc = "insert into customers values('" + serialno.Text + "','" + custname.Text + "','" + address.Text + "','" + phno.Text + "','" + eid.Text + "','" + event_type.Text + " ')"
    Dim command As MySqlClient.MySqlCommand = New MySqlClient.MySqlCommand(sqlc, con)
    command.ExecuteNonQuery()
    MessageBox.Show(sqlc)
    con.Close()

Else

    MsgBox("number already exists")
    dr.Close()

End If
con.Close()  'close connection before leaving
于 2013-03-22T15:27:15.230 回答