2016-03-07 83 views
1

我用C#.NET编写的应用程序有一个非常奇怪的SQL连接超时情况。C#SQL连接超时

SqlCommand.ExecuteNonQuery()正被用于在SQL Server中依次执行几个脚本。每个脚本都包含一个命令来创建一个表(根本不需要数据更新/插入/删除操作)。出于某种原因,在其中一个脚本中,SqlCommand.ExecuteNonQuery引发超时异常。

当我在SQL Server Management Studio中执行所有这些表的创建时,它们可以很好地立即执行。

有没有人有一个想法,当从应用程序创建表时,可能会导致超时?

所有SQL脚本,类似于像以下:

SQL:

create table dbo.Test 
( 
    Code varchar(10) not null 
, Name varchar(50) not null 
, other columns... 

    primary key 
, unique key 
, foreign key 
) 

这些脚本使用此代码C#运:

try 
{ 
    using (SqlConnection conSQL = new SqlConnection ("[connection string]")) 
    { 
    using (SqlCommand cmdSQL = new SqlCommand(sSQL, conSQL)) 
    { 
     cmdSQL.CommandTimeout = iTimeOut; 
     conSQL.Open(); 

     cmdSQL.ExecuteNonQuery(); // this is where it jumps to catch part and                    
           // throws out timeout exception 
     conSQL.Close(); 
    } 
    } 
} 
catch(Exception ex) 
{ 
    throw (ex); 
}    

这是发生在测试服务器上,这意味着当应用程序正在执行这些脚本时,服务器上没有其他事情发生。

+4

我们需要看到您的相关C#代码和SQL查询。 –

+0

试一下'cmdSQL.CommandTimeout = 0;' – Sachu

+0

你同意sql脚本很简单吧?我只是不明白为什么这一个脚本是超时的,其余的不是。要注意的是,Test sql服务器上没有其他任何运行,iTimeOut值为30秒。 – Andy

回答

1

您可以覆盖默认的超时通过更新machine.config,它可以在这里找到设置SQL事务:

%windir%\Microsoft.NET\Framework\[version]\config\machine.config 

64位

%windir%\Microsoft.NET\Framework64\[version]\config\machine.config 

machine.config添加结束或更新以下行:

<system.transactions> 
    <machineSettings maxTimeout="01:00:00" /> --> set this to desired value. 
</system.transactions> 
</configuration> 

如果abo已经无法正常工作,您可以通过代码SqlCommand指定Timeout setting还有:

using (SqlConnection connection = new SqlConnection(connectionString)) { 
    connection.Open(); 
    SqlCommand command = new SqlCommand(queryString, connection); 
    // Setting command timeout in seconds: 
    command.CommandTimeout = 3600; 
    try { 
     command.ExecuteNonQuery(); 
    } 
    catch (SqlException e) { 
     Console.WriteLine(e); 
    } 
    } 

更多信息here

+0

我已经提出了超时,直到1分钟,没有帮助。在我看来,设定更高的价值并不好。我试图找出发生这种情况的原因 – Andy

+0

我相信默认值是10分钟?所以不知道为什么你认为超过1分钟是不好的。然而让我们看看导致它的脚本的代码,也许我们可以看到发生了什么? – JanR

+0

更新了我的答案。 – JanR

0

就停止运行,并再次运行您的问题将得到解决....这通常只会在第一次出现大量文件时加载,这可能是Visual Studio中的错误。 新: 停止尝试刷新打开的网页(在浏览器中显示错误),而不是重新启动它...

+0

我已经做了好几次了,这些问题发生在应用程序的每次重新启动时。 – Andy