简体   繁体   English

C#SQL何时/如何关闭连接?

[英]C# SQL when/how do I close the connection?

I was using this code: 我正在使用此代码:

public class SQLConnection : IConnection
{
    private SqlConnection _sqlConnection = null;

    //bunch of interface implementations for my project

    //the destructor
    ~SQLConnection()
    {
        if(_sqlConnection != null)
        {
            if(_sqlConnection.State == ConnectionState.Open)
            {
                _sqlConnection.Close();
            }
            _sqlConnection.Dispose();
        }
    }
}

This was working well until some time ago, when I started receiving this error: Internal .Net Framework Data Provider error 1 直到前一段时间,当我开始收到此错误时,它一直运行良好: 内部.Net Framework数据提供程序错误1

After googling a bit, I found this link (the Caution part) and I think that's what's happening to me. 仔细搜索之后,我发现了此链接 (“警告”部分),我认为这就是我正在发生的事情。 My class was managing the connection state opening and closing each time, but now that it seems I can't manage it this way, is there any other way that I can do this without having to go to every function that I use the connection and call connection.Close() explicitly? 我的班级每次都在管理连接状态的打开和关闭,但是现在看来我无法用这种方式进行管理,还有其他方法可以做到这一点,而不必转到使用该连接的每个函数,并且显式地调用connection.Close()吗?

Always use 'using' for safely disposing the connections. 始终使用“使用”来安全处置连接。

using(var _sqlConnection = new SqlConnection())
{
     //code here
     _sqlConnection.Open();
}


//Safely disposed.

Also, it is never a good idea to use destructor explicitly in C# code unless you have unmanaged code. 另外,除非您拥有非托管代码,否则在C#代码中显式使用析构函数绝不是一个好主意。

You're probably receiving this error when one code is trying to access SQLConnection that has been already garbage collected. 当一个代码尝试访问已被垃圾回收的SQLConnection时,您可能会收到此错误。 This usually will happen in cases like this one 这种情况通常会发生在这种情况下

 SqlConnection sqlConn;

 using (var sqlConnection = new SqlConnection())
 {
    sqlConn = sqlConnection;
    sqlConnection.Open();
 }

 sqlConn.Close();

I know this example looks silly as it's overly simplified, but it happens often when programmers tend to share a connection object between Managing Classes. 我知道这个示例由于过于简化而显得很愚蠢,但是它经常发生在程序员倾向于在管理类之间共享连接对象时。 Look for any recent changes in your code. 查找您的代码中最近的更改。 Maybe you're passing an instance of a connection between multiple objects. 也许您正在传递多个对象之间的连接实例。 One of those objects gets Garbage Collected and in turn the connection gets disposed too. 这些对象之一将被回收,然后连接也将被丢弃。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM