MySqlConnection真的不能关闭 [英] 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.close
end sub
private sub FUNCTION2()
dim conn as new mysqlconnection(myconnstring)
....
conn.open
-- do something
conn.close
end sub
尽管我经常关闭所有连接,但它们在mysql服务器上仍保持打开"状态.我知道这是因为我正在使用MySQL管理工具来检查我按源代码逐行"打开了多少个连接.实际上,我有很多时间用户已超出'max_user_connections'资源(当前值:5)"我的主机只允许5个连接,但是我认为如果我编写良好的源代码,这不会有问题.所以我的问题是:为什么该死的"连接保持打开状态?预先谢谢你!
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!
推荐答案
请考虑将MySqlConnection操作包装在使用
语句中...
Consider wrapping your MySqlConnection operations in a Using
statement...
在该 Using ... new
语句中实例化的任何对象将由编译器正确处理.一旦出现该 End Using
语句,该对象就会失去作用域.
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
在这种情况下,您不必将Command和Reader封装在自己的 Using
中,但可以利用它们都实现了 IDisposable 的事实.代码>.
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
.
这篇关于MySqlConnection真的不能关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!