简体   繁体   中英

SQL Connection Open Exception

I am working on a project which, up until today, has been fine. However now when I run it and it goes through a few different Stored Procedure calls it is throwing an InvalidOperationException with the message The connection was not closed. The connection's current state is open. The connection was not closed. The connection's current state is open.

I get that I could put in a check to see if the connection is already open, but this code hasn't changed (it is under Version Control and isn't modified) so I'm looking for other potential explanations.

Could there be some lock in SQL which isn't being released? Is there a process which I should look out for and kill?

I can't really post the code as there is a lot of it, and it is split up into smaller methods which makes it harder to pull out individual items. Eg:

public SqlConnection Connection
{
    get
    {
        this._connection.Open();
        return _connection;
    }
}

public IDataReader RetrieveRecord(int Id)
{
    //SP
    SqlCommand cmd = this.Connection.CreateCommand();
cmd.CommandText = "SelectRecord";
    cmd.CommandType = CommandType.StoredProcedure;

    //Parameters
    cmd.Parameters.Add(new SqlParameter("@tID", Id));

    //instruct the data reader to close its connection when its Close method is         called by passing the CommandBehavior.CloseConnection 
    return cmd.ExecuteReader(CommandBehavior.CloseConnection);
}

Nothing massively complex, I just don't understand why this connection is now throwing an exception.

The DAL is not stable enough:

You open a Connection that is not closed if something goes wrong in RetrieveRecord.

You should create a new connection inside RetrieveRecord and close it there in a finally block.

Opening a connection is cheap thanks to Connection Pooling.

Problem is with the line

this._connection.Open();

Because you are trying to open an already opened connection.

Try this to check before opening a connection:

 if (this._connection.State == ConnectionState.Closed)
            this._connection.Open();

Sorted. Two reboots cleared whatever was keeping the connection open.

When you are talking about killing process, I think you know c# well.

You should always use

using()
{

}

Like:

using(SqlConnection con=new SqlConnection("connectionString"))
{
  // Do something with con
     using(SqlCommand cmd=new SqlCommand("cmdText",con))
     {
        // Do something with cmd
     }
}

You know that SqlCommand and SqlConnection implement IDisposable

So when you put those objects within using , the connection closing and clean up job is automatically done.

No need to close the connection manually in the code, since using will do the work for you.

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