.net - "There is already an open DataReader..."重用或处置数据库连接?

标签 .net vb.net connection-pooling

请帮助...。当我从 Mysql 表中选择数据时,它显示“已经有一个打开的 DataReader 与此连接关联,必须先关闭它。vb.net”Error showing..

Private Sub cmbJobCategoryVisa_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbJobCategoryVisa.SelectedIndexChanged
    ''"
    Dim MyCommand As New MySqlCommand("SELECT jobcategorycode FROM jobcategory WHERE jobcategory='" & Me.cmbJobCategoryVisa.SelectedItem & "'", MyConnection)
    Dim MyReader As MySqlDataReader = MyCommand.ExecuteReader
    While MyReader.Read
        If MyReader.HasRows = True Then
            Me.txtJobCategoryCodeVisa.Text = MyReader("jobcategorycode")
        End If
    End While
    MyReader.Close()
    MyCommand.Dispose()
End Sub

'''在执行下面的代码时,显示图像错误

    Private Sub txtEmpNo_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles txtEmpNo.Validating
    Dim MyCommand5 As New MySqlCommand("SELECT * FROM employeesmaster WHERE empno='" & Me.txtEmpNo.Text & "'", MyConnection)
    Dim MyDataReader5 As MySqlDataReader = MyCommand5.ExecuteReader
    If MyDataReader5.HasRows = True Then
        While MyDataReader5.Read
            Me.txtEmpName.Text = MyDataReader5("name")
            Me.cmbNationality.Text = MyDataReader5("nationality")
            Me.cmbJobCategoryVisa.Text = MyDataReader5("jobcategoryvisa")
            If Not IsDBNull(MyDataReader5("image")) Then
                Dim ImageData As Byte() = DirectCast(MyDataReader5("image"), Byte())
                Dim MemoryStream As New IO.MemoryStream(ImageData)
                Me.pbxEmpImage.Image = Image.FromStream(MemoryStream)
            Else
                Me.pbxEmpImage.Image = Nothing
            End If
        End While
    Else
    End If
    MyDataReader5.Close()
    MyCommand5.Dispose()
End Sub

最佳答案

很明显,您正在使用一个单一的全局连接,并且显然将其保持打开状态。如前所述,您不应重用或存储您的连接。创建连接的成本很低,并且 .NET 针对根据需要创建连接进行了优化。

您的代码中有很多东西没有被关闭和处置。应该是。 Disposing 不仅可以防止您的应用程序泄漏资源,而且如果为每个任务使用新创建的 DB 对象,也不会发生这种错误。

连接
由于在创建它们的过程中涉及 回旋,您可以编写一个函数来创建(并可能打开)一个新的 Connection 并避免在任何地方粘贴连接字符串。下面是一个使用 OleDB 的一般示例:

Public Function GetConnection(Optional usr As String = "admin",
                       Optional pw As String = "") As OleDbConnection
    Dim conStr As String
    conStr = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};User Id={1};Password={2};",
                      dbFile, usr, pw)

    Return New OleDbConnection(constr)
End Function

使用 block
在 Using block 中使用它,以便将其丢弃:

Using con As OleDb.OleDbConnection = GetConnection()
    Using cmd As New OleDbCommand(sql.Value, con)

        con.Open()
        Using rdr As OleDbDataReader = cmd.ExecuteReader()
           ' do stuff

        End Using      ' close and dispose of reader
    End Using          ' close and dispose of command
End Using              ' close, dispose of the Connection objects

每个 Using 语句都会创建一个新的目标对象,并将其放置在 block 的末尾。

一般来说,任何具有Dispose 方法的东西都可以而且应该在Using block 中使用以确保它被处理掉。这将包括代码中使用的MemoryStreamImage

使用 block 可以“堆叠”以指定多个对象并减少缩进(注意第一行末尾后的逗号):

Using con As OleDb.OleDbConnection = GetConnection(),
    cmd As New OleDbCommand(sql.Value, con)
    con.Open()
    ...
End Using       ' close and dispose of Connection and Command

有关详细信息,请参阅:


你能不能把这段代码转换成Mysql连接...我的连接字符串是...

对于基本 MySQL 连接:

' module level declaration 
Private MySQLDBase as String = "officeone"

Function GetConnection(Optional usr As String = "root",
                       Optional pw As String = "123456") As MySqlConnection
    Dim conStr As String
    conStr = String.Format("Server=localhost;Port=3306;Database={0};Uid={1}; Pwd={2};", 
         MySQLDBase, usr, pw)

    Return New MySqlConnection(constr)
End Function

个人对于MySql,我在方法中使用了一个类和一个ConnectionStringBuilder。我使用了很多很酷的选项,但这些选项因项目而异,例如数据库和默认应用程序登录。以上使用所有默认值。

关于.net - "There is already an open DataReader..."重用或处置数据库连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28213871/

相关文章:

.net - 格式化 json 文档

.NET应用程序内存使用情况-未使用的.NET以及未托管的内存和碎片数量很高

.net - 相同的 If() 和 If 产生不同的结果

asp.net - 使面板在 asp.net 中可见或不可见

asp.net - ODP.NET 连接池问题 - 数据库宕机后的容错

c# - 如何在事件处理程序内调用 WebBrowser 上的方法?

c# - 为什么 BufferedGraphics 绘制速度慢?

vb.net - 使用 Parallel.ForEach with/or async/await

mysql - 很难根据允许的最大连接数正确设置 RAILS_MAX_THREADS

java - 将数据从文件导入到具有 5 个节点的 Cassandra 集群会导致 BusyConnectionException