首页 > 解决方案 > “重置连接”是什么意思?System.Data.SqlClient.SqlException (0x80131904)

问题描述

我知道这有点模糊,但我无法确定问题所在。

当我对本地数据库运行一些代码时,它运行良好。当我使用远程数据库时出现错误。它发生在程序执行的中间。DBup 升级运行,然后手动查询失败,出现以下异常:

System.Data.SqlClient.SqlException (0x80131904):重置连接会导致与初始登录不同的状态。登录失败。用户“sa”登录失败。

我正在SqlConnection使用手动创建new SqlConnection(),我也在使用DbUp

我不确定我做错了什么。也不是从哪里开始调试这个。不会改变,ConnectionString我总是sa用来连接到数据库。

一个很好的问题是“重置连接”是什么意思?我是怎么做的?

标签: c#.netsql-serversqlconnectiondbup

解决方案


经过几个小时的反复试验,我得到了一段最小的代码来重现错误

string dbName = "TESTDB";
Run("master", $"CREATE DATABASE [{dbName}]");
Run(dbName, $"ALTER DATABASE [{dbName}] COLLATE Latin1_General_100_CI_AS");
Run(dbName, "PRINT 'HELLO'");

void Run(string catalog, string script)
{
    var cnxStr = new SqlConnectionStringBuilder
    {
        DataSource = serverAndInstance,
        UserID = user,
        Password = password,
        InitialCatalog = catalog
    };

    using var cn = new SqlConnection(cnxStr.ToString());
    using var cm = cn.CreateCommand();
    cn.Open();
    cm.CommandText = script;
    cm.ExecuteNonQuery();
}

完整的堆栈跟踪是

Unhandled Exception: System.Data.SqlClient.SqlException: Resetting the connection results in a different state than the initial login. The login fails.
Login failed for user 'user'.
Cannot continue the execution because the session is in the kill state.
A severe error occurred on the current command.  The results, if any, should be discarded.
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
   at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
   at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
...

如果我将第一个更改Run(dbName...Run("master"...它运行良好。所以它与ALTER DATABASE在同一个数据库的上下文中运行有关


推荐阅读