2014-02-10 182 views
1

我正在研究一直到今天爲止的項目。但是現在,當我運行它,它經歷了幾個不同的Stored Procedure調用它與消息The connection was not closed. The connection's current state is open.SQL連接打開異常

,我感到我可以把在一個檢查,看看是否連接已經打開拋出InvalidOperationException,但是這個代碼不是招沒有改變(它在Version Control下,沒有修改),所以我正在尋找其他潛在的解釋。

SQL中沒有被釋放的鎖嗎?是否有一個我應該注意並殺死的過程?

我不能真的發佈代碼,因爲它有很多它,它被分成更小的方法,這使得更難以拉出單個項目。例如:

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); 
} 

沒什麼大問題,我只是不明白爲什麼這個連接現在拋出一個異常。

+0

您正在公開SqlConnection Connection()函數中打開連接,但從未在程序中關閉。 –

回答

0

排序。兩次重新啓動都清除了保持連接打開的所有內容。

+0

我仍然會考慮重構代碼,以便很好地關閉連接。 – Koen

+1

我100%同意。問題幾乎總是如此,因爲說服項目經理花時間重寫技術上可行的東西是值得的。 – MattR

+0

知道這種感覺。但是,在遇到這個問題之後,你可能有一點要說服他。無論如何,祝你好運! ;-) – Koen

0

問題是與線

this._connection.Open(); 

因爲你試圖打開一個已經打開的連接。

試試這個打開連接前檢查:

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

Yip我意識到這一點,正如我在原帖中所說的那樣,但我正在尋找任何其他潛在的鎖定考慮因素,因爲該班級沒有改變,並且在幾個月內工作正常。 – MattR

1

的DAL不夠穩定:

你打開,如果出現錯誤的RetrieveRecord未關閉的連接。

你應該在RetrieveRecord裏創建一個新的連接,並在finally塊中關閉它。

由於Connection Pooling的關係,打開連接很便宜。

0

當你在談論殺人過程時,我認爲你很瞭解c#。

你應該總是使用

using() 
{ 

} 

像:

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

你知道的SqlCommand和SqlConnection的實施IDisposable

所以,當你把內using這些對象,連接關閉和清潔自動完成作業。

無需在代碼中手動關閉連接,因爲using將爲您完成工作。