繁体   English   中英

C# SQL 连接超时

[英]C# SQL connection timeout

我有一个非常奇怪的 SQL 连接超时案例,来自一个用 C# .NET 编写的应用程序。

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

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

有谁知道从应用程序创建表时可能导致超时的原因是什么?

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

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

您可以通过更新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> 

如果上述方法不起作用,您也可以通过代码为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);
     }
  }

更多信息在这里

只要停止运行并再次运行,您的问题就会得到解决...。通常只有当他们加载大量文件时才第一次发生,也许这是visual studio中的错误。 新:停止后尝试刷新打开的网页(在显示错误的浏览器中)而不是再次重新启动它...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM