C# 如何从 SQL 连接字符串设置查询超时

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1198951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 10:40:56  来源:igfitidea点击:

how to set the query timeout from SQL connection string

c#sql-server

提问by

I want to set the querytimeout from the connection string. not the connection timeout, is it possible?

我想从连接字符串设置查询超时。不是连接超时,有可能吗?

回答by gbn

No. It's per command, not per connection.

不,它是每个命令,而不是每个连接。

Edit, May 2013

编辑,2013 年 5 月

As requested in comment:

根据评论中的要求:

Some more notes about commands and execution time outs in SQL Server (DBA.SE). And more SO stuff: What happens to an uncommitted transaction when the connection is closed?

关于SQL Server (DBA.SE) 中的命令和执行超时的更多说明。还有更多的东西:当连接关闭时未提交的事务会发生什么?

回答by AnthonyWJones

See:- ConnectionStringscontent on this subject. There is no default command timeout property.

请参阅:-有关此主题的ConnectionStrings内容。没有默认的命令超时属性。

回答by Iain Hoult

You can only set the connection timeout on the connection string, the timeout for your query would normally be on the command timeout. (Assuming we are talking .net here, I can't really tell from your question).

您只能在连接字符串上设置连接超时,您的查询超时通常在命令超时上。(假设我们在这里谈论 .net,我真的无法从您的问题中看出)。

However the command timeout has no effect when the command is executed against a context connection (a SqlConnection opened with "context connection=true" in the connection string).

但是,当针对上下文连接(在连接字符串中使用“context connection=true”打开的 SqlConnection)执行命令时,命令超时不起作用。

回答by parfilko

Only from code:

仅来自代码:

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

回答by hamid reza Heydari

you can set Timeout in connection string (time for Establish connection between client and sql). commandTimeout is set per command but its default time is 30 secend

您可以在连接字符串中设置超时(客户端和sql之间建立连接的时间)。commandTimeout 是按命令设置的,但它的默认时间是 30 秒