Home » Ado.Net » Mastering SqlConnection

Mastering SqlConnection

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.

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

or

using (var connection = new SqlConnection())
{
	connection.ConnectionString = @"Data Source=PATRICK-PC\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True";
	connection.Open();
	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.

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

If you like my article, think to buy my annual book, professionally edited by a proofreader. directly from me or on Amazon. I also wrote a TypeScript book called Holistic TypeScript

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.