MySQL Connection Pool Count

前端 未结 1 1745
余生分开走
余生分开走 2021-01-25 13:04

I have started to receive an error with my VB.NET application:

Timeout Expired. The timeout elapsed prior to obtaining a connection from the pool. This ma

相关标签:
1条回答
  • 2021-01-25 13:32

    There are several things in your code.

    • First turn on Option Strict. The function is declared to return a string, but you are trying to return Object with Return result
    • Everything which implements a Dispose method ought to be used inside a Using block. This allows you to declare and initialize an object, use it and dispose of it at the end.
    • Parameters.Add is better than AddWithValue. The later forces the DB Provider to guess the datatype based on the data.
    • Depending on the load and whether that method is used a lot, you could load the data to a DataTable and do lookups on that rather than query the DB over and over.

    The core issue is (probably) that you do not dispose of the DBCommand object. Look at the constructor you use:

    Dim cmdx As New MySqlCommand(cmdTextx, connx)
    

    The DBCommand object is passed a reference to the connection. Even though you explicitly dispose of the connection, cmdx still has a reference to it, and it was not disposed. Using blocks make it simple to be sure things are disposed:

    Dim sql = "Select `Cert` From `Courses` WHERE `ID`=@ID"
    
    Using dbCon As New MySqlConnection(MySQLConnStr)
        Using cmd As New MySqlCommand(sql, dbCon)
            cmd.Parameters.Add("@Id", MySqlDbType.Int32).Value = CourseTypeID
            dbCon.Open()
            Dim result = cmd.ExecuteScalar
    
            If result Is Nothing OrElse result Is DBNull.Value Then
                Return String.Empty
            Else
                Return result.ToString()
            End If
        End Using           ' close, dispose of conn
    End Using               ' dispose of DBCommand
    

    To reduce indentation, you can "stack" items into one Using block:

    Using connx As New MySqlConnection(MySQLConnStr),
        cmd As New MySqlCommand(sql, connx)
        ...
    End Using
    

    Note the comma at the end of the first line.

    I'd be surprised if this was not the cause of your leak (of course all the code would need to be changed).

    0 讨论(0)
提交回复
热议问题