如何从SQL连接字符串中设置查询超时时间

47

我想从连接字符串中设置查询超时时间。 不是连接超时时间,这是否可能?

8个回答

45

1
提供任何涵盖此内容的文档链接将非常有用。 - Richard Ev

14

您一直可以通过 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"

上面的连接字符串将命令超时设置为1分钟(60秒)。
希望这个对你有用。

5

参见:ConnectionStrings 中关于此主题的内容。没有默认命令超时属性。


4
你只能在连接字符串中设置连接超时时间,查询的超时时间通常在命令超时时间中设置。(假设我们在这里讨论 .net,我不能从你的问题中确定)。然而,当对上下文连接(在连接字符串中使用“context connection=true”打开的 SqlConnection)执行命令时,命令超时时间没有任何作用。

谢谢大家,这很有道理,因为连接字符串可以用于其他查询。 - shlomtzi

3

我已经尝试了不同的参数命令超时时间在下面的连接字符串中,并且每次都按预期工作。

Data Source=Your_Db_Server;Initial Catalog=Your_DB;Integrated Security=true;TrustServerCertificate=true;Connect Timeout=600;Command Timeout=120

1
仅限于代码:

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; }
                }
            }
        }
    }
 
    //....
 
 }


-1

我在FollowCode中找到了答案:

 SqlDataAdapter da = new SqlDataAdapter(Query, ConnectionString);
 da.SelectCommand.CommandTimeout = queryTimeoutInSeconds;

-3

你可以在连接字符串中设置超时时间(客户端和 SQL 之间建立连接所需的时间)。CommandTimeout是针对每个命令设置的,但其默认时间为30秒


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接