如何解决c#中的连接超时错误

本文关键字:连接 超时 错误 何解决 解决 | 更新日期: 2023-09-27 18:08:07

我是c#和SQL Server新手;我用T-SQL和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");

我得到这个错误:

超时过期。操作完成前的超时时间或服务器没有响应。

My connection string this:

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

我怎么解决这个问题?谢谢。

如何解决c#中的连接超时错误

使用CommandTimeout或优化StoredProcedure

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

如果你不知道如何设置超时值,就不要设置。

Microsoft使可选项具有良好定义的值。

超时问题有两项你必须检查。

数据库:如该

--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不能用来运行大查询