Export (0) Print
Expand All
6 out of 33 rated this helpful - Rate this topic

SqlConnection Class

Represents an open connection to a SQL Server database. This class cannot be inherited.

Namespace: System.Data.SqlClient
Assembly: System.Data (in system.data.dll)

public sealed class SqlConnection : DbConnection, ICloneable
public final class SqlConnection extends DbConnection implements ICloneable
public final class SqlConnection extends DbConnection implements ICloneable
Not applicable.

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. For a list of these values, see the SqlConnection constructor.

If the SqlConnection goes out of scope, it remains open. Therefore, you must explicitly close the connection by calling Close or Dispose. Close and Dispose are functionally equivalent. If the connection pooling value Pooling is set to true or yes, the underlying connection is returned back to the connection pool. On the other hand, if Pooling is set to false or no, the underlying connection to the server is actually closed.

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 connection As New SqlConnection(connectionString)
    connection.Open()
    ' Do work here; connection closed on following line.
End Using
using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();
        // Do work here; connection closed on following line.
    }
NoteNote:

To deploy high-performance applications, you must use connection pooling. When you use the .NET Framework Data Provider for SQL Server, you do not have to enable connection pooling because the provider manages this automatically, although you can modify some settings. For more information, see Connection Pooling for the .NET Framework Data Provider for SQL Server.

If a SqlException is generated by the method executing a SqlCommand, the SqlConnection remains open when the severity level is 19 or less. When the severity level is 20 or greater, the server ordinarily closes the SqlConnection. However, the user can reopen the connection and continue.

An application that creates an instance of the SqlConnection object can require all direct and indirect callers to have sufficient permission to the code by setting declarative or imperative security demands. SqlConnection makes security demands using the SqlClientPermission object. Users can verify that their code has sufficient permissions by using the SqlClientPermissionAttribute object. Users and administrators can also use the Code Access Security Policy Tool (Caspol.exe) to modify security policy at the machine, user, and enterprise levels. For more information, see Security in the .NET Framework. For an example demonstrating how to use security demands, see Code Access Security and ADO.NET.

NoteNote:

If you are using Microsoft .NET Framework version 1.0, the FullTrust named permission set is required to connect to SQL Server by using Open. This requirement does not apply if you are using .NET Framework version 1.1 or later. For more information, see Requesting Permissions and Named Permission Sets.

For more information about handling warning and informational messages from the server, see Working with Connection Events.

Caution noteCaution:

ADO.NET 2.0 does not support Asynchronous commands over shared memory for SQL Server 2000 or lower. However, you can force TCP instead of shared memory. You can do that by prefixing tcp: to the server name in the connection string or you can use localhost.

TopicLocation
How to: Create Connections to SQL Server DatabasesData Access in Visual Studio

The following example creates a SqlCommand and a SqlConnection. The SqlConnection is opened and set as the Connection for the SqlCommand. The example then calls ExecuteNonQuery, and closes the connection. To accomplish this, the ExecuteNonQuery is passed a connection string and a query string that is a Transact-SQL INSERT statement.

private static void OpenSqlConnection()
{
    string connectionString = GetConnectionString();
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();
        Console.WriteLine("ServerVersion: {0}", connection.ServerVersion);
        Console.WriteLine("State: {0}", connection.State);
    }
}

static private string GetConnectionString()
{
    // To avoid storing the connection string in your code, 
    // you can retrieve it from a configuration file, using the 
    // System.Configuration.ConfigurationSettings.AppSettings property 
    return "Data Source=(local);Initial Catalog=AdventureWorks;"
        + "Integrated Security=SSPI;";
}

System.Object
   System.MarshalByRefObject
     System.ComponentModel.Component
       System.Data.Common.DbConnection
        System.Data.SqlClient.SqlConnection
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows 98, Windows Server 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The Microsoft .NET Framework 3.0 is supported on Windows Vista, Microsoft Windows XP SP2, and Windows Server 2003 SP1.

.NET Framework

Supported in: 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 2.0, 1.0
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.