ADO.NET - SQL Connection Class

SQL Connection Class

A SqlConnection object represents a unique session to a SQL Server data source. With a client/server database system, it is equivalent to a network connection to the server. SqlConnection is used together with SqlDataAdapter and SqlCommand to increase performance when connecting to a Microsoft SQL Server database. For all third-party SQL Server products, and other OLE DB-supported data sources, use OleDbConnection.

When you create an instance of SqlConnection, all properties are set to their initial values.

To ensure that connections are always closed, open the connection inside of a using block, as shown in the following code fragment. Doing so ensures that the connection is automatically closed when the code exits the block.

    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();
        // Do work here; connection closed on following line.
    }

For More information See SqlConnection Class

SqlConnection.ConnectionString Property

SqlConnection.ConnectionString Property :Gets or sets the string used to open a SQL Server database.

The connection string that includes the source database name, and other parameters needed to establish the initial connection. The default value is an empty string.

You can use the ConnectionString property to connect to a database. The following example illustrates a typical connection string.

  "Data Source=MyServerName;Initial Catalog=MyDatabaseName;Integrated Security=true;"

Connecting to SQL Server using windows authentication

  "Data Source=MyServerName;Initial Catalog=MyDatabaseName;Integrated Security=true;"

Connecting to SQL Server using SQL authentication

  "Data Source=MyServerName;Initial Catalog=MyDatabaseName;User Id=MyUserName;Password=MyPassword;"

Connecting to SQL Server via IP Address

  "Data Source=IP_Address;Initial Catalog=MyDatabaseName;User Id=MyUserName;Password=MyPassword;"

Attach a database file, located in the data directory

  "Data Source=MyServerName;AttachDbFilename=|DataDirectory|MyDatabaseName.mdf;Integrated Security=true;"