Sql server 如何模拟数据库连接超时

Sql server 如何模拟数据库连接超时,sql-server,sql-server-2008,connection,timeout,Sql Server,Sql Server 2008,Connection,Timeout,我们的一些连接正在超时(可能),如果连接到SQL超时,我们需要以某种方式处理代码。我知道,可以使用WAITFORDELAY轻松模拟命令超时,但如何模拟连接超时?我只是设法模拟了连接超时 首先在sql server上执行以下查询(我是在ssms中执行的) 从Visual Studio启动了以下代码 namespace TimeOut_Test_Project_ASP { public partial class _Default : System.Web.UI.Page {

我们的一些连接正在超时(可能),如果连接到SQL超时,我们需要以某种方式处理代码。我知道,可以使用WAITFORDELAY轻松模拟命令超时,但如何模拟连接超时?

我只是设法模拟了连接超时

首先在sql server上执行以下查询(我是在ssms中执行的)

从Visual Studio启动了以下代码

namespace TimeOut_Test_Project_ASP
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string cs = "Data Source=ServerName;Initial Catalog=my_Test_DB; Integrated Security=SSPI;Connect Timeout=3";

            using (SqlConnection con = new SqlConnection(cs))
            {
                SqlCommand cmd = new SqlCommand("SELECT * FROM dbo.TableName", con);

                con.Open();
                GridView1.DataSource = cmd.ExecuteReader();
                GridView1.DataBind();
            }
        }
    }
}
错误堆栈

Server Error in '/' Application.

The wait operation timed out

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.ComponentModel.Win32Exception: The wait operation timed out

Stack Trace: 


[Win32Exception (0x80004005): The wait operation timed out]

[SqlException (0x80131904): Connection Timeout Expired.  The timeout period elapsed during the post-login phase.  The connection could have timed out while waiting for server to complete the login process and respond; Or it could have timed out while attempting to create multiple active connections.  The duration spent while attempting to connect to this server was - [Pre-Login] initialization=309; handshake=1; [Login] initialization=0; authentication=1; [Post-Login] complete=2002; ]
   System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +5340655
   System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +244
   System.Data.SqlClient.TdsParserStateObject.ReadSniError(TdsParserStateObject stateObj, UInt32 error) +601
   System.Data.SqlClient.TdsParserStateObject.ReadSniSyncOverAsync() +256
   System.Data.SqlClient.TdsParserStateObject.TryReadNetworkPacket() +39
   System.Data.SqlClient.TdsParserStateObject.TryPrepareBuffer() +64
   System.Data.SqlClient.TdsParserStateObject.TryReadByte(Byte& value) +86
   System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +222
   System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +69
   System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK) +30
   System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover) +317
   System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout) +891
   System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance) +307
   System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData) +518
   System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) +278
   System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) +38
   System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) +732
   System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) +85
   System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) +1057
   System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) +78
   System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) +196
   System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +146
   System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +16
   System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry) +94
   System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) +110
   System.Data.SqlClient.SqlConnection.Open() +96
   First_Project_ASP._Default.Page_Load(Object sender, EventArgs e) in D:\c# Projects\First Project ASP\First Project ASP\Default.aspx.cs:22
   System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +51
   System.Web.UI.Control.OnLoad(EventArgs e) +92
   System.Web.UI.Control.LoadRecursive() +54
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +772
将数据库设置为多用途模式

ALTER DATABASE [my_Test_DB] SET MULTI_USER;
看了之后,我想尝试连接到错误的主机,结果成功了

保持用户名、数据库等正常,但将“主机”参数更改为您可以控制的有效URL/IP,但用户名和密码将不起作用

连接将超时

这样,您就不必以任何方式更改数据库,所以它非常好


使用其他不正确的连接参数也可能有效,例如数据库名称。

您还可以尝试将超时设置为1秒,然后查看是否引发超时异常。请注意,1是可以设置的最低值。将“连接超时=1;”添加到连接字符串中。请注意,这是一个连接超时,而不是一个查询超时,它是一个完全不同的东西,并且不是在连接字符串中设置的。请注意,如果在1秒之内建立连接,那么这可能会也可能不会实际模拟它


在尝试建立连接之前,我还尝试断开网络电缆与我的开发人员计算机的连接。

我怀疑这是否是SQL连接超时,因为在您的情况下,连接确实建立到SQL,但是,命令对象由于锁定而超时。我正在寻找SQL级别的超时,当它在发送命令之前第一次尝试建立与SQL的连接时。@MurtazaMandvi您是对的,这不是连接超时,而是查询超时错误,现在看一看,我101%确定这是连接超时,因为在启动应用程序代码之前,我已将数据库更改为单用户模式。它尝试打开连接,并在3秒钟后超时,因为我已在连接字符串中设置属性3秒钟。有时响应可能会在毫秒内返回,因此它不会总是100%模拟超时情况
ALTER DATABASE [my_Test_DB] SET MULTI_USER;