【问题标题】:MysqlException was unhandled DataReader with this connection must be closed vb.netMysqlException 未处理 DataReader 必须关闭此连接 vb.net
【发布时间】:2013-02-05 19:26:13
【问题描述】:

我遇到过这个问题:

错误:已经有一个打开的 DataReader 与此 Connection 关联,必须先关闭它。

请看我的代码:

 Dim sqlQuery As String = "SELECT * FROM users"
    Dim myAdapter As New MySqlDataAdapter

    If txtUsername.Text = String.Empty And txtPassword.Text = String.Empty Then
        MsgBox("Enter username and password", MsgBoxStyle.Exclamation, "Tea Sparkle POS")
    Else
        Dim sqlquerry = "Select * From users where username = '" + txtUsername.Text + "' And password= '" + txtPassword.Text + "'"
        Dim myCommand As New MySqlCommand()
        myCommand.Connection = SQLConnection
        myCommand.CommandText = sqlquerry
        'Starting The Query
        myAdapter.SelectCommand = myCommand
        Dim mydata As MySqlDataReader
        mydata = myCommand.ExecuteReader()
        'To check the Username and password and to validate the login a
        If mydata.HasRows = 0 Then
            MsgBox("Invalid Login")
            txtPassword.Clear()
            txtUsername.Clear()
        Else
            Dim authorityid = 0
            While mydata.Read()
                authorityid = mydata.GetInt32("authorityid")
            End While
            MsgBox("Welcome " + txtUsername.Text + "!")
            If authorityid = 1 Then
                MainForm.Show()
            Else
                MainForm.Show()
            End If
            Me.Hide()
        End If
    End If


    Private Sub Login_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

    SQLConnection.ConnectionString = ServerString

    Try
        If SQLConnection.State = ConnectionState.Closed Then
            SQLConnection.Open()
        Else
            SQLConnection.Close()
        End If
    Catch ex As Exception
        MsgBox(ex.ToString)
    End Try

End Sub

这个错误在这一行:

 mydata = myCommand.ExecuteReader()

这有什么问题?任何帮助都非常感谢。

【问题讨论】:

  • 您需要使用try/catch 块并发布exception 消息。
  • @Brian 我已经更新了我的代码。我忘了把我的表单加载中的内容放在里面

标签: mysql vb.net datareader


【解决方案1】:

这是怎么回事?

嗯,看起来您正在重用现有连接:

myCommand.Connection = SQLConnection

不要那样做。每次需要与数据库通信时创建一个新连接,并在完成后关闭它,使用 Using 语句确保即使抛出异常也会关闭它。

此外,为您的命令使用Using 语句,为您的读者使用另一个 - 这些都是您应该关闭的资源。

哦,您似乎也在 UI 线程中执行此操作,这是一个坏主意,因为在数据库访问正在进行时您的 UI 将无响应。

【讨论】:

  • 您好,您能给我举一些关于使用Using语句的例子吗?谢谢。
  • using (SqlCommand sqlCommand = new SqlCommand()){ } 是 Jon 所说的。
  • @Brian 我认为这是针对 c# 的?
  • @bEtTyBarnes - 这个例子是 C#,是的。 VB.NET 看起来像这样:Using stream As New MemoryStream(buffer, False)。当然,在您的情况下,您不会使用 MemoryStream
  • @bEtTyBarnes:您是否搜索过“using statement c# msdn”(或 VB 的等价物)?
猜你喜欢
  • 1970-01-01
  • 2020-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多