C#SQL连接超时
我用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);
}
这是发生在测试服务器上,这意味着当应用程序正在执行这些脚本时,服务器上没有其他事情发生。
您可以覆盖默认的超时通过更新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
就停止运行,并再次运行您的问题将得到解决....这通常只会在第一次出现大量文件时加载,这可能是Visual Studio中的错误。 新: 停止尝试刷新打开的网页(在浏览器中显示错误),而不是重新启动它...
我已经做了好几次了,这些问题发生在应用程序的每次重新启动时。 – Andy
我们需要看到您的相关C#代码和SQL查询。 –
试一下'cmdSQL.CommandTimeout = 0;' – Sachu
你同意sql脚本很简单吧?我只是不明白为什么这一个脚本是超时的,其余的不是。要注意的是,Test sql服务器上没有其他任何运行,iTimeOut值为30秒。 – Andy