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

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
 
M

Marcel Müller

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top