解決SqlTransaction用盡的問題(SQL處理逾時)

來源:互聯網
上載者:User

有時候程式處理的資料量比較小時,四平八穩,一切安然無恙,但資料量一大,原先潛伏的問題就暴露無遺了。
原訪問資料庫的代碼為:
 1SqlConnection conn = new SqlConnection(strConn);
 2conn.Open();
 3SqlTransaction trans = conn.BeginTransaction();
 4try
 5{
 6    CEngine.ExecuteNonQuery(trans,CommandType.Text,sql);
 7    trans.Commit();
 8}
 9catch(SqlException ex)
10{
11    trans.Rollback();
12    ErrorCode = ex.Number;
13    Info = "資料操作失敗:" + ex.Message;
14}
15finally
16{
17    trans.Dispose();
18    conn.Close();
19}
20
21
22
運行時,一旦出現資料量過大或處理時間較長,則系統會提示出錯。錯誤提示為“SqlTransaction已用完;他再也不能使用。”

開始時,我懷疑是跟記憶體有關。因為系統需要做好交易回復的準備,每執行一條插入或修改的SQL,都要有一定的開銷,資料量一大,恐怕就吃不消了。不過我查了一下SQL SERVER的資料,未見提到記憶體的問題。
後來想到,資料庫連接SqlTransaction有個時間問題。預設是15秒。資料量大的時候,這個時間非常可能就不夠了。於是改為:
 1SqlConnection conn = new SqlConnection(strConn);
 2conn.Open();
 3SqlTransaction trans = conn.BeginTransaction();
 4try
 5{
 6    SqlCommand cmd = new SqlCommand();
 7    cmd.CommandType = CommandType.Text;
 8    //串連時限改為300秒
 9    cmd.CommandTimeout = 300;
10    cmd.CommandText = sql;
11    cmd.Connection = conn;
12    cmd.Transaction = trans;
13    cmd.ExecuteNonQuery();
14    trans.Commit();
15}
16catch(SqlException ex)
17{
18    trans.Rollback();
19    ErrorCode = ex.Number;
20    Info = "資料操作失敗:" + ex.Message;
21}
22finally
23{
24    trans.Dispose();
25    conn.Close();
26}
修改後在測試,問題解決:)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.