I'm trying to set up a method that will attempt to connect to a SQL Server first on the default port (1433) and then on a different port like 7777 upon failure.
I want to avoid rebuilding the connection string and trying to connect again in case of failure because this method will be executed at a configured interval and I want to eliminate as much overhead as possible.
I have tried the following (courtesy of ConnectionStrings)
public void EstablishConnection()
{
string ConnectionString = "Data Source=127.0.0.1; Failover Partner=127.0.0.1,7777; Initial Catalog=foo;Connection Timeout = 3; Persist Security Info =True;User ID=<id>;Password=<password>";
try
{
SqlConnection Connection = new SqlConnection(ConnectionString);
Connection.Open();
}
catch (SqlException)
{
// Connection failed
}
}
But based off of this article and my testing, it does not work the way I intended.
I could easily solve this by doing the following:
public void EstablishConnection()
{
string ConnectionString = "Data Source=127.0.0.1;Initial Catalog=foo;Connection Timeout = 3; Persist Security Info =True;User ID=<id>;Password=<password>";
try
{
SqlConnection Connection = new SqlConnection(ConnectionString);
Connection.Open();
}
catch (SqlException)
{
try
{
string ConnectionString = "Data Source=127.0.0.1,7777;Initial Catalog=foo;Connection Timeout = 3; Persist Security Info =True;User ID=<id>;Password=<password>";
SqlConnection Connection = new SqlConnection(ConnectionString);
Connection.Open();
}
catch (SqlException)
{
// Connection failed
}
}
}
But this feels like spaghetti code and overall bad practice.
Also in the real application I am not fetching the full connection string from a configuration file, I am pulling the parameters from a configuration file and building the configuration string from there.