0
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
4

3 回答 3

1

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

MSDN 说

在使用 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 类可以使用连接池基础结构,它可以帮助管理像连接这样的宝贵资源

于 2013-09-26T08:51:49.200 回答
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
于 2013-09-26T08:53:15.403 回答
0

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

例子:

"Server=Server;Database=MyDatabase;Trusted_Connection=True;MultipleActiveResultSets=true;"
于 2017-02-14T18:21:15.577 回答