Can't connect to a MS SQL Server 2017 Express from dotnet core 2.2 console application.
Checked Server Configuration as in Connection to SQL Server Works Sometimes
I have installed a new Microsoft SQL Server 2017 Express. Then tested the connection to this server with a console application (under .Net Framework 4.7.1). Works!.
Then I created a console application under Dot Net Core 2.2. Installed NuGet package System.Data.SqlClient and tried connect to the sql server using the same connection string I tested before and got a timeout error. How can this be fixed? (I also used the package Microsoft.Data.SqlClient, with the same result.)
If I try to connect to another SQL-Server (2008) the connection is established without problems.
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();
}
}
}
Following Exception occured:
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; '
Forcing to use named pipes by specifying np:
qualifier in the server
parameter in the connection string does the job.
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();
try to catch SQLServer timeout exceptions :
try
{
// some code
}
catch (SqlException ex) when (ex.Number == -2) // -2 is a sql timeout
{
// handle timeout
}
this might hep timeout
To enable remote access for SQLExpress, you have to Configure Express to accept remote connections
In ConnectionString
:
database
should not be empty. If have everything well configured, the easiest way to fix timeout
is:
dbConnection.ConnectionTimeout = 0;
this will let ADO.NET try/wait again and again, until it really fails.
Here is a good example:
Server=sampleServer\SQLEXPRESS,samplePort;Database=sampleDB;Persist Security Info=True;User ID=sa;Password=12345678;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.