开发者

MySqlConnection really not close

i've a huge problem. Take a look to this sample code

private sub FUNCTION1()
      dim conn as new mysqlconnection(myconnstring)
      conn.open
      ---- do something
      FUNCTION2()
      ---- 
      conn.clos开发者_JS百科e
end sub

private sub FUNCTION2()
     dim conn as new mysqlconnection(myconnstring)
     .... 
     conn.open
     -- do something
     conn.close
end sub

Despite i close regulary all my connection, they remains "open" on the mysql server. I know this because i'm using MySQL Administration tool to check how many connection i open "line by line" of my source code. In fact i get a lot of time "user has exceeded the 'max_user_connections' resource (current value: 5)" My hoster permit ONLY 5 connection, but i think that if i write GOOD source code, this cannot be a problem. So my question is: why that "damn" connections remain open ?? Thank you in advance!


Consider wrapping your MySqlConnection operations in a Using statement...

Any object that you instantiate within that Using ... new statement will be disposed of properly by the compiler. Once that End Using statement appears, the object goes out of scop. Any objects that are declared with in the Using block will need to be disposed of by the developer, as per normal.

Using conn As New MySqlConnection(myConnString)
  Using cmd As New MySqlCommand("SELECT * FROM Employees", conn)
    conn.Open()
      Using rdr As MySqlDataReader = cmd.ExecuteReader()
        While rdr.Read()
          Console.WriteLine(rdr(0))
        End While
      End Using
  End Using
End Using

In this case, you don't HAVE to encase your Command and Reader in their own Using, but it allows you to take advantage of the fact that they all implement IDisposable.


Try calling conn.Dispose() and then setting it to null. On another note, are you opening a connection in Function1 and Function2 also as it appears that you're creating 2 connections. If that's the case try to implement a singleton pattern to manage your connections.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜