Which of these two is the best way to get the connection string from app.config file

  • Thread starter Thread starter Tony Johansson
  • Start date Start date
T

Tony Johansson

Below I have two ways 1 and 2 that show how I can get the SqlConnection from
the configuration file.
I just wonder if any of these two is more suitable then the other. I can't
see the point to use the one that is marked 1 but
I assume that there is some advantage for each of these two.

1.
private SqlConnection GetSqlConnection()
{
ConnectionStringSettings settings =
ConfigurationManager.ConnectionStrings[BLACKJACK];
if (settings == null)
{
throw new ArgumentException(BLACKJACK + " was not found as
a connectionstring name");
}

DbProviderFactory factory =
DbProviderFactories.GetFactory(settings.ProviderName);
DbConnection conn = factory.CreateConnection();
conn.ConnectionString = settings.ConnectionString;

return conn as SqlConnection;
}


2.
private SqlConnection GetSqlConnection()
{
ConnectionStringSettings settings =
ConfigurationManager.ConnectionStrings[BLACKJACK];
if (settings == null)
{
throw new ArgumentException(BLACKJACK + " was not found as
a connectionstring name");
}

SqlConnection sqlConnection = new SqlConnection();
sqlConnection.ConnectionString = settings.ConnectionString;

return sqlConnection;
}

//Tony
 
Going the factory route provides some flexibility, but the calling code
needs to be prepared to take advantage of that flexibility (e.g. by
using DbConnection instead of SqlConnection).

Well, at the point where stored procedures and statement parameters come
into play the story ends, because the MS SQL driver requires a
different syntax for the SQL statement parameters. This could become a
show stopper.


Marcel
 
Back
Top