Mastering SqlConnection<!-- --> | <!-- -->Patrick Desjardins Blog
Patrick Desjardins Blog
Patrick Desjardins picture from a conference

Mastering SqlConnection

Posted on: September 26, 2011

The SqlConnection object is an object that derive of DbConnection. It opens the connection between the application and the database. It's also inherit of IDisposable because of DbConnection.

1var connection = new SqlConnection();
2connection.ConnectionString = @"Data Source=PATRICK-PC\\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True";


1using (var connection = new SqlConnection()) {
2 connection.ConnectionString = @"Data Source=PATRICK-PC\\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True";
3 connection.Open();
4 connection.Close();

These two snippets of code illustrate the creation of a connection. Both of them were using connection string from a string but the value can be directly loaded from the app.config or web.config.

1ConnectionStringSettings connectionStringSettings = ConfigurationManager.ConnectionStrings["ApplicationServices"];
2using (var connection = new SqlConnection(connectionStringSettings.ConnectionString)) {
3 connection.Open();
4 connection.Close();
2 <connectionStrings>
3 <add name="ApplicationServices" connectionString="Data Source=PATRICK-PC\\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True" providerName="System.Data.SqlClient" />
4 </connectionStrings>
5... ...