无法关闭MySQL数据库连接

时间:2015-01-21 15:43:21

标签: c# mysql asp.net .net

我是ASP.NET的新手并且自己学习问题是我在页面加载时成功连接到我的数据库我的意思是当调用Page_Load方法时:

MySqlConnection con = null;

protected void Page_Load(object sender, EventArgs e)
{
    if (con == null)
    {
        ConnectDataBase();
    }
}

并假设它在页面加载时成功连接!现在我想关闭连接:

  con.Close();

所以我应该在哪里Close()因为我对这项工作不熟悉所以我不知道我是否可以使用Page_Close方法,在那里我可以关闭连接。

有人可以告诉我任何其他正确的方法或想法。问题是我只想关闭连接!

2 个答案:

答案 0 :(得分:5)

您必须在完成连接后立即关闭连接。如果您有一些需要数据库的代码,请打开连接,获取数据并断开连接。

最好使用using,因为它会为您关闭并处理连接(即使发生异常):

using (MySqlConnection conn = new MySqlConnection())
{
    // open the connection and use it
}

// here it is closed and disposed

答案 1 :(得分:1)

正如蒂姆所说,你应该只在需要时打开它,并使用using这样的声明:

protected void Page_Load(object sender, EventArgs e)
{
    using(var con = new MySqlConnection(<args>))
    {

    } //at the end of this block, the connection will be Disposed automatically.
}