简体   繁体   中英

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

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?

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.

You're probably receiving this error when one code is trying to access SQLConnection that has been already garbage collected. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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