SQL Server How to make SQL connection timeout shorter

ztyzrc3y  于 2023-11-16  发布在  其他
关注(0)|答案(1)|浏览(122)

I`m working on my tiny project and trying to connect my windows forms app to SQL Server. Here is code of my connection class:

public class DatabaseConnection
{
    private string connectionString;
    private SqlConnection connection;

    public DatabaseConnection()
    {
        connectionString = "Data Source=xxx.xxx.x.x;Initial Catalog=xxxxxx;User ID=xxxxxx;Password=xxxxxxxx;Connect Timeout=5";
        connection = new SqlConnection(connectionString);
    }

    public bool OpenConnection()
    {
        try
        {
            connection.Open();
            return true;
        }
        catch (Exception)
        {
            connectionString = "Data Source=xxxxxxxxxxxx;Initial Catalog=xxxxxxx;User ID=xxxxxxx;Password=xxxxxxxx;Connect Timeout=5";
            connection = new SqlConnection(connectionString);

            try
            {
                connection.Open();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }

    public void CloseConnection()
    {
        connection.Close();
    }

    public SqlConnection GetConnection()
    {
        return connection;
    }
}

I'm trying to make the connection timeout to 5 seconds instead of 30, because when I'm loading my app and it is trying to connect by the first IP and it fails it's waiting 30 seconds for server to send error and then trying to connect by the second IP. My question is how to make the delay time to 5 seconds

I've tried different ways, first is to add a connection timeout property to connection string: connectionString = "Data Source=xxxxxxxxx;Initial Catalog=xxxxx;User ID=xxxxxx;Password=xxxxxxxxxx;Connect Timeout=5";

The second way is to set lock timeout to 5000 ms before connection.open()

try
{
    using (SqlCommand command = new SqlCommand("SET LOCK_TIMEOUT 5000", connection))
    {
        connection.Open();
    }
    return true;
}
c2e8gylq

c2e8gylq1#

First of all, you should mask passwords, IPs, usernames etc if you post them in a public forum.

However back to your question: you got the wrong property in your connection string

connectionString = "Data Source=XX.XXX.XXX:XXX;Initial Catalog=Hotsiy_NP;User ID=XXXX;Password=XXXXXXX;Connection Timeout=5";

Its connection timeout not connect timeout: see https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlconnection.connectiontimeout?view=dotnet-plat-ext-7.0 for reference

相关问题