MysqlException 未处理 DataReader 必须关闭此连接 vb.net

标签 mysql vb.net datareader

我遇到过这个问题:

错误:已经有一个与此连接关联的打开的 DataReader,必须先将其关闭。

请看我的代码:

 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()

这是怎么回事?非常感谢任何帮助。

最佳答案

What's wrong with this?

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

myCommand.Connection = SQLConnection

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

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

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

关于MysqlException 未处理 DataReader 必须关闭此连接 vb.net,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14715319/

相关文章:

javascript - 在 Javascript 中获取 session 值?

vb.net - 如何阻止 DateTimePicker 显示今天的日期

从数据表创建 C# 对象

mysql - 如何快速地在 MySQL 中的多列中进行全文搜索?

mysql - 如何从IP连接到MySQL数据库?

php - 是否有必要取消设置 php 密码变量?

.net - 使用表格副本

python - 如何在 Python 中连接到 MySQL 数据库?

c# - 使用列表从 MySql 数据库检索信息出现异常 "Index was outside the bounds of the array."

c# - 加载异步 WP8.1 : Partial result