我想从连接字符串中设置查询超时时间。 不是连接超时时间,这是否可能?
您一直可以通过 SqlClient 连接字符串指定连接超时时间,这适用于与数据库服务器建立连接,而非执行命令/运行查询。
默认的连接超时时间为 15 秒。
随着 Microsoft.Data.SqlClient v2.1 的发布,它引入了“Command Timeout”连接字符串属性,以覆盖此属性的默认值(30秒),如果需要的话。
因此,现在可以通过连接字符串设置默认的命令超时时间。
要使用此新功能,您必须通过向项目文件添加以下内容,在 EF Core 3 和 5 上显式依赖于更新的 SqlClient 包:
<PackageReference Include="Microsoft.Data.SqlClient" Version="2.1.0" />
此外,您必须更新连接字符串以增加默认命令超时时间 - 请记住,这将适用于整个应用程序,除非通过设置SqlCommand.CommandTimeout属性在代码中覆盖。
连接字符串示例:
"YourDatabaseAlias": "Server={serverURL}; Initial Catalog={db}; Integrated Security=true; Command Timeout=60"
我已经尝试了不同的参数命令超时时间在下面的连接字符串中,并且每次都按预期工作。
Data Source=Your_Db_Server;Initial Catalog=Your_DB;Integrated Security=true;TrustServerCertificate=true;Connect Timeout=600;Command Timeout=120
namespace xxx.DsXxxTableAdapters {
partial class ZzzTableAdapter
{
public void SetTimeout(int timeout)
{
if (this.Adapter.DeleteCommand != null) { this.Adapter.DeleteCommand.CommandTimeout = timeout; }
if (this.Adapter.InsertCommand != null) { this.Adapter.InsertCommand.CommandTimeout = timeout; }
if (this.Adapter.UpdateCommand != null) { this.Adapter.UpdateCommand.CommandTimeout = timeout; }
if (this._commandCollection == null) { this.InitCommandCollection(); }
if (this._commandCollection != null)
{
foreach (System.Data.SqlClient.SqlCommand item in this._commandCollection)
{
if (item != null)
{ item.CommandTimeout = timeout; }
}
}
}
}
//....
}
我在FollowCode中找到了答案:
SqlDataAdapter da = new SqlDataAdapter(Query, ConnectionString);
da.SelectCommand.CommandTimeout = queryTimeoutInSeconds;
你可以在连接字符串中设置超时时间(客户端和 SQL 之间建立连接所需的时间)。CommandTimeout是针对每个命令设置的,但其默认时间为30秒