繁体   English   中英

点网核心–如何解决:MSSQL 2017超时错误(.Net 4.7.1不会发生)

[英]Dot net Core – How to fix: TimeOut-Error to MSSQL 2017 (which does not happen with .Net 4.7.1)

无法从dotnet core 2.2控制台应用程序连接到MS SQL Server 2017 Express。

连接到SQL Server时检查服务器配置有时会起作用

我已经安装了新的Microsoft SQL Server 2017 Express。 然后使用控制台应用程序(在.Net Framework 4.7.1下)测试与该服务器的连接。 作品!。

然后,我在Dot Net Core 2.2下创建了一个控制台应用程序。 安装了NuGet包System.Data.SqlClient并尝试使用我之前测试过的相同连接字符串连接到sql服务器,并收到超时错误。 如何解决? (我还使用了包Microsoft.Data.SqlClient,结果相同。)

如果我尝试连接到另一个SQL Server(2008),则建立连接不会出现问题。

using System;
using System.Data.SqlClient;

namespace ConsoleClient
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Connecting");

            using (var conn = new SqlConnection(@"server=<IP>\SQLEXPRESS;user id=sa;password=<PASSWORD>;database="))
            {
                Console.WriteLine("Try to open connection");

                conn.Open();

                Console.WriteLine("Connection opened");
            }
            Console.ReadLine();
        }
    }
}

发生以下异常:

Microsoft.Data.SqlClient.SqlException: 'Connection Timeout Expired.  The timeout period elapsed while attempting to consume the pre-login handshake acknowledgement.  This could be because the pre-login handshake failed or the server was unable to respond back in time.  The duration spent while attempting to connect to this server was - [Pre-Login] initialization=21064; handshake=50; '

通过在连接字符串的server参数中指定np:限定符来强制使用命名管道。


Console.WriteLine("Connecting");

using (var conn = new SqlConnection(@"server=np:<IP>\SQLEXPRESS;user id=sa;password=<PASSWORD>;database="))
{
    Console.WriteLine("Try to open connection");

    conn.Open();

    Console.WriteLine("Connection opened");
}
Console.ReadLine();

尝试捕获SQLServer超时异常:

      try
        {
            // some code
        }
        catch (SqlException ex) when (ex.Number == -2)  // -2 is a sql timeout
        {
            // handle timeout
        }

这可能会超时

要为SQLExpress启用远程访问,必须将Express配置为接受远程连接

ConnectionString

  1. 需要一个用于SQLExpress服务器的端口。
  2. 参数database不能为空。

如果一切都配置正确,则解决timeout的最简单方法是:

dbConnection.ConnectionTimeout = 0;

这将使ADO.NET反复尝试/等待,直到它真正失败为止。

这是一个很好的例子:

Server=sampleServer\SQLEXPRESS,samplePort;Database=sampleDB;Persist Security Info=True;User ID=sa;Password=12345678;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM