2016-09-21 42 views
-4

我是C#和SQL Server的新手;我寫在T-SQL一個簡單的存儲過程,並在C#與下代碼調用:如何解決C#中的連接超時錯誤?

da = new SqlDataAdapter("select_equals_Cycle", con); 
da.SelectCommand.CommandType = CommandType.StoredProcedure; 
ds = new DataSet(); 
da.Fill(ds, "select_equals_Cycle"); 

,但在這條線:

da.Fill(ds, "select_equals_Cycle"); 

我得到這個錯誤:

Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.

我的連接字符串是:

string conn = "Data Source=.;Initial Catalog=ClubEatc;Integrated Security=True;Connect Timeout=30;"; 

我該如何解決這個問題?謝謝。

+6

你需要找到超時的根本原因。是否因爲你試圖從數據庫中加載超過千兆字節?你在等鎖嗎?你有一個非常緩慢的網絡?你有*網絡嗎?你總是可以增加超時時間,但除非你掌握了它爲什麼不能成爲修復的原因,更像是一個繃帶。 –

+0

那麼如果所有其他的都失敗了,你可以增加連接字符串的超時時間 - 如果這個過程運行的時間很長 - 但是如果一個存儲過程運行超過30秒來填充一個數據集,那麼這個過程效率會很低,設置您需要的負載。 – Adwaenyth

+0

嘗試此鏈接中的步驟http://stackoverflow.com/questions/8602395/timeout-expired-the-timeout-period-elapsed-prior-to-completion-of-the-operation –

回答

0

使用的CommandTimeout或優化的StoredProcedure

da.SelectCommand.CommandTimeout = 180; // default is 30 seconds 
0

不要設置超時值,如果你不知道如何配置它。

Microsoft使可選的定義好的值。

超時問題有兩個項目,你必須檢查。

數據庫: 例如MSSQL

--the code below ran in Query of Sql Server 
--this code snippet will show you all the advance options 
Exec sp_configure 'show advanced options',1 
recogfigure 
-- this code snippet configure the seconds of the query wait 
-- this configuration means that if the memory couldn't used to query -- the big query, sql server will wait for some seconds 
-- this option usually use the default value made by Microsoft 
-- the default value about how many seconds of formula is the estimated query -- -- time multiply by 25, and if the memory still couldn't used for querying. 
-- then throw TimeOut Exception 
Exec sp_configure 'query wait', 200; 
ReCONFIGURE 
-- the end 

// the timeout configuration about C# 
SqlConnection.ConnectionTimeout = 200 
// here is the Document: 
// get the time to wait while trying to establish a connection before 
// terminating the attempt and generating and error 
// the Unit of the property is second 
// 0 is no limit 

掃描完代碼片段後,會發現兩個原因會導致異常。

  1. 您的代碼無法建立連接。

  2. 你的機器內存安裝SQL Server不能用來運行大型查詢