错误显示已经有一个与此命令关联的打开的DataReader必须先关闭

时间:2013-09-26 08:47:28

标签: vb.net

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

    Dim n As Integer = 0
    str = "select Vote from vote where party='Green'"
    cmd = New SqlCommand(str, con)
    con.Open()
    dr = cmd.ExecuteReader()
    if dr.HasRows Then
      dr.Read()
      n = dr("Vote").ToString()
      n = n + 1
      Label8.Text = n.ToString()
    End If

    str = "update Vote set vote='" + n.ToString() + "' where party='Green'"
    cmd = New SqlCommand(str, con)
    cmd.ExecuteNonQuery()
    dr.Read()
    cmd.Dispose()
    con.Close()

End Sub

3 个答案:

答案 0 :(得分:1)

这条消息似乎很清楚。在尝试将连接用于其他操作之前,您必须关闭DataReader

MSDN says

  

在使用SqlDataReader时,关联的SqlConnection是   忙于服务SqlDataReader,没有其他操作可以   在SqlConnection上执行而不是关闭它。情况就是这样   直到调用SqlDataReader的Close方法。例如,   在调用Close之前,您无法检索输出参数。

....
dr.Close()
str = "update Vote set vote='" + n.ToString() + "' where party='Green'"
cmd = New SqlCommand(str, con)
cmd.ExecuteNonQuery()
' ??? dr.Read()
cmd.Dispose()
con.Close()

顺便说一下,使用ExecuteScalar可以简化整个代码,以检索最后一个投票值并转储DataReader

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

    Dim n As Integer = 0
    str = "select Vote from vote where party='Green'"
    Using cmd = New SqlCommand(str, con)
        con.Open()
        Dim n as Integer
        Dim result = cmd.ExecuteScalar()
        if result IsNot Nothing Then
            n = Convert.ToInt32(result) + 1
        else
            n = 1
        End If
        Label8.Text = n.ToString()
        str = "update Vote set vote='" + n.ToString() + "' where party='Green'"
        cmd.CommandText = str
        cmd.ExecuteNonQuery()
        con.Close()
    End Using
End Sub

在这种情况下,您使用全局连接对象,应该避免这种情况。请记住,在需要使用连接时创建,打开,使用和销毁连接总是更好。 SqlClient类可以使用Connection Pooling基础结构,它可以帮助管理宝贵的资源,如连接

答案 1 :(得分:0)

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

  try

    Dim n As Integer = 0

    str = "select Vote from vote where party='Green'"
    cmd = New SqlCommand(str, con)
    con.Open()

    dr.Close()
    dr = cmd.ExecuteReader()
    if dr.HasRows Then
      dr.Read()
      n = dr("Vote").ToString()
      n = n + 1
      Label8.Text = n.ToString()
    End If

    str = "update Vote set vote='" + n.ToString() + "' where party='Green'"
    cmd = New SqlCommand(str, con)
    cmd.ExecuteNonQuery()
    dr.Read()

   Finally

    cmd.Dispose()
    con.Close()

  End Try

End Sub

答案 2 :(得分:0)

将多个活动结果集添加到您的连接字符串,如下所示

示例:

"Server=Server;Database=MyDatabase;Trusted_Connection=True;MultipleActiveResultSets=true;"