Tom*_*ana 4 .net c# mysql mysql-connector
人们在早期使用MySQL时所学到的一些事情,即在使用后立即关闭连接很重要,但为什么这么重要呢?那么,如果我们做一个网站,它可以节省一些服务器资源(如描述在这里),但为什么我们应该做的是在.NET桌面应用程序?它是否与Web应用程序共享相同的问题?或者还有其他人吗?
如果使用连接池,则不会通过调用关闭物理连接con.Close,只需告诉池可以使用此连接.如果你在一个循环中调用数据库东西,如果你不关闭它们,你会很快得到像"太多开放连接"这样的例外.
检查一下:
for (int i = 0; i < 1000; i++)
{
var con = new SqlConnection(Properties.Settings.Default.ConnectionString);
con.Open();
var cmd = new SqlCommand("Select 1", con);
var rd = cmd.ExecuteReader();
while (rd.Read())
Console.WriteLine("{0}) {1}", i, rd.GetInt32(0));
}
Run Code Online (Sandbox Code Playgroud)
一个可能的例外:
超时已过期.从池中获取连接之前经过的超时时间.这可能是因为所有池连接都在使用中并且达到了最大池大小.
顺便说一下,a也是如此MySqlConnection.
这是正确的方法,using在所有类型的实现上使用语句IDsiposable:
using (var con = new SqlConnection(Properties.Settings.Default.ConnectionString))
{
con.Open();
for (int i = 0; i < 1000; i++)
{
using(var cmd = new SqlCommand("Select 1", con))
using (var rd = cmd.ExecuteReader())
while (rd.Read())
Console.WriteLine("{0}) {1}", i, rd.GetInt32(0));
}
}// no need to close it with the using statement, will be done in connection.Dispose
Run Code Online (Sandbox Code Playgroud)