Can't connect to SQLLocalDB sometimes when PC is offline - c#

We are using SQLLocalDB to connect to a local database. No network access is required - C# Client application is on the same machine as SQLLocalDB. Sometimes I get the following error (only seems to happen on some PCs):
Microsoft.SqlServer.Management.Common.ConnectionFailureException: Failed to connect to server (localdb)\myserverinstancename. ---> System.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=27888; handshake=0; ---> System.ComponentModel.Win32Exception: The wait operation timed out
Oddly, it seems to happen if the PC is offline, and if connected to any sort of internet connection and retried, the issue goes away. However, in most cases the connection works fine even when there is no connection.
The closest I've found to my problem is this: Connection to SQL Server Works Sometimes
But that is discussing full SQL Server, rather than SQLLocalDB, and the solution uses "Sql Server Configuration Manager", which doens't work with SQLLocalDB.
My questions:
Does SQLLocalDb use IPv6/TCP for some reason, even when on the same PC?
Is there a way to change these settings for SQLLocalDB?
Or is there a different cause for this issue?
Edit: With help from some of the comments below I realised that the line that fails is when it calls a database creation script. The initial attempt at connection seems to work, but when I run my creation script it throws a "Failed to connect to server".
/// This line works
var server = new Server("(localdb)\myserverinstancename");
/// this line works 99% of the time, but sometimes "failed to connect to server"
server.ConnectionContext.ExecuteNonQuery(databaseCreationScript);

Related

SQL Server LocalDB no longer allows multiple connections

I'm using Windows 11 and I have a SQL Server LocalDB database that is accessed by a desktop application and Power BI desktop. It used to work normally but suddenly I started seeing connection issues, as described below. The SQL server has a named instance accessed using SQL Server authentication.
Sequence:
Restart the machine, check the instance from the command prompt
C:\Users\xxx>sqllocaldb info "Instance"
Name: Instance
Version: 11.0.3000.0
Shared name:
Owner: Domain\UserName
Auto-create: No
State: Stopped
Last start time: 1/16/2023 10:04:30 AM
Instance pipe name:
Open Power BI Desktop, click Add data and try to add anything in the database, all is good and the connection is fine.
Check the instance state from the command prompt: same as above (so I can query the database from Power BI, while the instance state is 'Stopped')! How?.
Open the desktop application, the application cannot connect to the database and throws an exception at the Connection.Open method with this error message:
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Error occurred during LocalDB instance startup: SQL Server process failed to start.
And the following message is repeated in the Windows Application event log:
Windows API call WaitForMultipleObjects returned error code: 575. Windows system error message is: {Application Error}
The application was unable to start correctly (0x%lx). Click OK to close the application.
Reported at line: 3621.
Try to start the instance from the command prompt:
sqllocaldb start "Instance"
Start of LocalDB instance "Instance" failed because of the following error:
Error occurred during LocalDB instance startup: SQL Server process failed to start.
Restart the machine again. Checking the state of the instance in the command prompt gives the same result as above.
Start the application, it starts normally, no connection errors.
Check the Instance state:
Name: Instance
Version: 11.0.3000.0
Shared name:
Owner: Domain\UserName
Auto-create: No
State: Running
Last start time: 1/17/2023 3:18:49 PM
Instance pipe name: np:\\.\pipe\LOCALDB#28451FA3\tsql\query
Start Power BI and try to connect to the database, it won’t connect. The following error appears
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Error occurred during LocalDB instance startup: SQL Server process failed to start.
And this message comes up in the event viewer
Windows API call WaitForMultipleObjects returned error code: 575. Windows system error message is: {Application Error}
The application was unable to start correctly (0x%lx). Click OK to close the application.
Reported at line: 3621.
I've searching in Google and Microsoft for a couple of days, but I cannot find anyone having the same issue. I suspect a recent update to Windows 11 that caused these issues, as it was running perfectly before.
Both the desktop application and Power BI should be able to access the database simultaneously without issues.

MySQl Command timeout during read operation from table having 40+ million records

We have a strange situation where we are getting below error when using mysql with EF6.
MySql.Data.MySqlClient.MySqlException: Fatal error encountered during command execution. --->
MySql.Data.MySqlClient.MySqlException: Fatal error encountered attempting to read the resultset. --->
MySql.Data.MySqlClient.MySqlException: Reading from the stream has failed. --->
System.IO.IOException: Unable to read data from the transport connection: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. --->
System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
If, we take the generated query from EF6 to MySql workbench, it execute without any error in 75 sec.
But, when running in application it throws error within 30 seconds.
The table has huge records, which will take more than 70 sec to return with rows. But thats fine only thing is "it should not throw error due to read timeout failure".
Tried solution:
We have changed the Global as well as mysql settings for read timeout to 99999 but, still it shows the same error.
SET GLOBAL net_read_timeout=999999;
SET net_read_timeout = 999999
You can increase the timeout (default is 30) in either the connection string or the DbContext Database object.
C#
DbContext.Database.CommandTimeout = 999;
Connection string
Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;
default command timeout=999;

C# Sql Connection can not connect to server

I'm trying to connect SQL server in my virtual machine with following connection string: "Server=qqvm;Database=a_test;Integrated Security=False;User Id=sa;Password=<pass>;Connect Timeout=0"
Firstly I had 'Network connection' exception with inner 'Access Denied' exception with empty stack trace. I did some digging and enabled 'Named Pipes' in SQL Configuration Manager.
After that I got this exception:
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=11281; handshake=1;
However, I'm still able to connect via SQL Management Studio to that server remotely. Any ideas?
Finally in my case specifying IP address instead of qqvm name solved the problem. Still don't know why, though. It worked a week ago.

connecting to mirrored databases after failover

I have two mirrored SQL Servers (A and B for example).
I wrote a simple C# program (connect via SqlConnection), which insert rows into DB. When I make failover on server A, the program throws exception, then I try reconnect, and get exception by timeout (**A connection was successfully established with the server, but then an error occurred during the pre-login handshake. (provider: SSL Provider, error: 0**).
When I restart the app, the connection is successfully established (to server B). Next, I make failover on B server, and program throws exception, then I try to reconnect, and its work - connection to A witout restarting program.
My connection string:
Data Source=SERVER_A;Failover Partner=SERVER_B;Initial Catalog=TEST_DB;persist security info=True;user id=USER_LOGIN;password=USER_PASS;Connection Timeout=60;
I also try to set big timeout (60 seconds), and try to clear All sqlconnection pools, clear single pool by connection, but it is not working.
Interesting fact: if I use domain login and password, all works fine!
(user SID are same)
Hard to tell what your exact problem is. Perhaps it's that failovers aren't instant, and can't transfer query state - see https://dba.stackexchange.com/questions/27528/can-availability-groups-provide-seamless-failover-with-no-query-failures. If your application immediately retries the query the failover node may therefore still be in the process of taking over and therefore not ready to accept connections.

error 26 cannot connect to database

I took an old software made by someone else, which need to connect to a database with the .mdf extension.
But when I run the software, I have an error 26. I have obviously checked Google and it seems the the main problem is the firewall. But if I disable it the problem doesn't dissapear.
Here is the code for connect the database :
DataClasses1DataContext db = new DataClasses1DataContext(Environment.CurrentDirectory + "\\bddgestionvin.mdf");
I've noticed, when I try to connect the database with the datacontext class it fail too with the same error 26. (see attached screenshot below)
The string connection used by this class is :
Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\bddgestionvin.mdf;Integrated Security=True;Connect `Timeout=30;User Instance=True`
I know I'm a little vague but I never did that kind of stuff (connect to a .mdf database) And the code is not mine, feel free the ask further explanation / code. Any help is welcome !
P.S The error message is
SqlException was unhandled A network-related or instance-specific
error occurred while establishing a connection to SQL Server. The
server was not found or was not accessible. Verify that the instance
name is correct and that SQL Server is configured to allow remote
connections. (provider: SQL Network Interfaces, error: 26 - Error
Locating Server/Instance Specified)
(Sorry for the french software)
Hi I don't know you may see these steps. Make sure that these steps should pass.
The reason that we get this error message is the client stack could
not receive SSRP response UDP packet from SQL Browser. It's easy to
isolate the issue. Here are the steps:
1) Make sure your server name is correct, e.g., no typo on the name.
2) Make sure your instance name is correct and there is actually such
an instance on your target machine. [Update: Some application converts
\ to . If you are not sure about your application, please try both
Server\Instance and Server\Instance in your connection string]
3) Make sure the server machine is reachable, e.g, DNS can be resolve
correctly, you are able to ping the server (not always true).
4) Make sure SQL Browser service is running on the server.
5) If firewall is enabled on the server, you need to put
sqlbrowser.exe and/or UDP port 1434 into exception.
You can read more from here
You can also try PortQry and validate your firewall does not block SQL Browser UDP packet
A network-related or instance-specific error occurred while establishing a connection to SQL Server. Failed to establish a connection with SQL Server.
The server was not found or was not accessible.
May be server is stopped, you don't have permission to access the server, or the instance name is not correct .
Verify that the instance name is correct and that SQL Server is configured to allow remote connections.
Please goto SSMS and try connecting the server. Verify the SQL Server is running and your account is configured to access the service.
(provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
Thanks

Categories

Resources