Search code examples
c#sql-serversqlconnection

How to quickly check a SQL connection without waiting 30 seconds for connection.open();


If I've got a connection string based on user input and I want to quickly determine if it's a valid input. I've done some research and it seems people use .Open() to check the connection. However in my console app this check takes ~30 seconds before throwing the catch statement. Is there a faster way to do this?

EDIT: A few of you have suggested setting the timeout to a low value like 1. Isn't this cause for concern? Considering the default is set to 30 I'd be afraid of timing out too early on a valid - yet slow - connection.

Here's my code if you need it:

while (sqlManager == null)
{
    try
    {
        sqlManager = new SqlManager(Console.ReadLine());
    }
    catch
    {
        sqlManager = null;
        Console.WriteLine("values entered could not be used to establish a connection, please try again: ");
    }
}
public class SqlManager
{
    public SqlManager(string userEntry)
    {
        string server;
        string db;
        if (userEntry == "")
        {
            server = Properties.Settings.Default.SqlServer;
            db = Properties.Settings.Default.SqlDatabase;
        }
        else
        {
            var splits = userEntry.Split(' ');
            server = splits[0];
            db = splits[1];
        }
        SqlConnection con = new SqlConnection($"Server= {server}; Database= {db}; Integrated Security=True;");
        con.Open();
    }
}

Solution

  • Use the ConnectionTimeout property to define a shorter wait time:

    https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectiontimeout(v=vs.110).aspx

    The default is 15 or 30 seconds, the current documentation mentions 15... You can set it to any larger or smaller number. 0 would mean to wait infinitely.

    Actually changing the default is a bit tricky, because the ConnectionTimeout property on the SqlConnection class is read-only. You have to specify it as a part of the connection string, or use a connection string builder, like this:

    var connstr = new SqlConnectionStringBuilder
    {
        DataSource = "servername",
        IntegratedSecurity = true,
        ApplicationIntent = ApplicationIntent.ReadOnly,
        ApplicationName = "appname",
        InitialCatalog = "db",
        ConnectTimeout = 2
    }.ConnectionString;
    
    using (var conn = new SqlConnection { ConnectionString = connstr })
    {                        
        conn.Open();
    }