Share via


SqlConnection Class

Definition

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

public ref class SqlConnection sealed : System::Data::Common::DbConnection, ICloneable
public sealed class SqlConnection : System.Data.Common.DbConnection, ICloneable
type SqlConnection = class
    inherit DbConnection
    interface ICloneable
Public NotInheritable Class SqlConnection
Inherits DbConnection
Implements ICloneable
Inheritance
SqlConnection
Implements

Examples

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. To accomplish this, the ExecuteNonQuery is passed a connection string and a query string that is a Transact-SQL INSERT statement. The connection is closed automatically when the code exits the using block.

using System;
using System.Data;
using Microsoft.Data.SqlClient;

namespace SqlCommandCS
{
    class Program
    {
        static void Main()
        {
            string str = "Data Source=(local);Initial Catalog=Northwind;"
                + "Integrated Security=SSPI";
            string qs = "SELECT OrderID, CustomerID FROM dbo.Orders;";
            CreateCommand(qs, str);
        }
        private static void CreateCommand(string queryString,
            string connectionString)
        {
            using (SqlConnection connection = new SqlConnection(
                       connectionString))
            {
                SqlCommand command = new SqlCommand(queryString, connection);
                command.Connection.Open();
                command.ExecuteNonQuery();
            }
        }
    }
}

Remarks

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.

See ConnectionString for a list of the keywords in a connection string.

If the SqlConnection goes out of scope, it won't be closed. 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.

Note

Login and logout events will not be raised on the server when a connection is fetched from or returned to the connection pool, because the connection is not actually closed when it is returned to the connection pool. For more information, see SQL Server Connection Pooling (ADO.NET).

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.  
    }  

Note

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 SQL Server Connection Pooling (ADO.NET).

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 Caspol.exe (Code Access Security Policy Tool) to modify security policy at the machine, user, and enterprise levels. For more information, see Security in .NET. For an example demonstrating how to use security demands, see Code Access Security and ADO.NET.

For more information about handling warning and informational messages from the server, see Connection Events. For more information about SQL Server engine errors and error messages, see Database Engine Events and Errors.

Caution

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.

Constructors

SqlConnection()

Initializes a new instance of the SqlConnection class.

SqlConnection(String)

Initializes a new instance of the SqlConnection class when given a string that contains the connection string.

SqlConnection(String, SqlCredential)

Initializes a new instance of the SqlConnection class given a connection string, that does not use Integrated Security = true and a SqlCredential object that contains the user ID and password.

Properties

AccessToken

Gets or sets the access token for the connection.

AccessTokenCallback

Gets or sets the access token callback for the connection.

CanCreateBatch

Gets a value that indicates whether this SqlConnection instance supports the DbBatch class.

ClientConnectionId

The connection ID of the most recent connection attempt, regardless of whether the attempt succeeded or failed.

ColumnEncryptionKeyCacheTtl

Gets or sets the time-to-live for column encryption key entries in the column encryption key cache for the Always Encrypted feature. The default value is 2 hours. 0 means no caching at all.

ColumnEncryptionQueryMetadataCacheEnabled

Gets or sets a value that indicates whether query metadata caching is enabled (true) or not (false) for parameterized queries running against Always Encrypted enabled databases. The default value is true.

ColumnEncryptionTrustedMasterKeyPaths

Allows you to set a list of trusted key paths for a database server. If while processing an application query the driver receives a key path that is not on the list, the query will fail. This property provides additional protection against security attacks that involve a compromised SQL Server providing fake key paths, which may lead to leaking key store credentials.

CommandTimeout

Gets the default wait time (in seconds) before terminating the attempt to execute a command and generating an error. The default is 30 seconds.

ConnectionString

Gets or sets the string used to open a SQL Server database.

ConnectionTimeout

Gets the time to wait while trying to establish a connection before terminating the attempt and generating an error.

Credential

Gets or sets the SqlCredential object for this connection.

Database

Gets the name of the current database or the database to be used after a connection is opened.

DataSource

Gets the name of the instance of SQL Server to which to connect.

FireInfoMessageEventOnUserErrors

Gets or sets the FireInfoMessageEventOnUserErrors property.

PacketSize

Gets the size (in bytes) of network packets used to communicate with an instance of SQL Server.

RetryLogicProvider

Gets or sets a value that specifies the SqlRetryLogicBaseProvider object bound to this command.

ServerProcessId

Gets the server process Id (SPID) of the active connection.

ServerVersion

Gets a string that contains the version of the instance of SQL Server to which the client is connected.

State

Indicates the state of the SqlConnection during the most recent network operation performed on the connection.

StatisticsEnabled

When set to true, enables statistics gathering for the current connection.

WorkstationId

Gets a string that identifies the database client.

Methods

BeginTransaction()

Starts a database transaction.

BeginTransaction(IsolationLevel)

Starts a database transaction with the specified isolation level.

BeginTransaction(IsolationLevel, String)

Starts a database transaction with the specified isolation level and transaction name.

BeginTransaction(String)

Starts a database transaction with the specified transaction name.

ChangeDatabase(String)

Changes the current database for an open SqlConnection.

ChangePassword(String, SqlCredential, SecureString)

Changes the SQL Server password for the user indicated in the SqlCredential object.

ChangePassword(String, String)

Changes the SQL Server password for the user indicated in the connection string to the supplied new password.

ClearAllPools()

Empties the connection pool.

ClearPool(SqlConnection)

Empties the connection pool associated with the specified connection.

Close()

Closes the connection to the database. This is the preferred method of closing any open connection.

CreateCommand()

Creates and returns a SqlCommand object associated with the SqlConnection.

EnlistDistributedTransaction(ITransaction)

Enlists in the specified transaction as a distributed transaction.

EnlistTransaction(Transaction)

Enlists in the specified transaction as a distributed transaction.

GetSchema()

Returns schema information for the data source of this SqlConnection. For more information about scheme, see SQL Server Schema Collections.

GetSchema(String)

Returns schema information for the data source of this SqlConnection using the specified string for the schema name.

GetSchema(String, String[])

Returns schema information for the data source of this SqlConnection using the specified string for the schema name and the specified string array for the restriction values.

Open()

Opens a database connection with the property settings specified by the ConnectionString.

Open(SqlConnectionOverrides)

Opens a database connection with the property settings specified by the ConnectionString.

OpenAsync(CancellationToken)

An asynchronous version of Open(), which opens a database connection with the property settings specified by the ConnectionString. The cancellation token can be used to request that the operation be abandoned before the connection timeout elapses. Exceptions will be propagated via the returned Task. If the connection timeout time elapses without successfully connecting, the returned Task will be marked as faulted with an Exception. The implementation returns a Task without blocking the calling thread for both pooled and non-pooled connections.

RegisterColumnEncryptionKeyStoreProviders(IDictionary<String,SqlColumnEncryptionKeyStoreProvider>)

Registers the column encryption key store providers. This function should only be called once in an app. This does shallow copying of the dictionary so that the app cannot alter the custom provider list once it has been set.

The built-in column master key store providers that are available for the Windows Certificate Store, CNG Store and CSP are pre-registered.

RegisterColumnEncryptionKeyStoreProvidersOnConnection(IDictionary<String,SqlColumnEncryptionKeyStoreProvider>)

Registers the encryption key store providers on the SqlConnection instance. If this function has been called, any providers registered using the static RegisterColumnEncryptionKeyStoreProviders(IDictionary<String,SqlColumnEncryptionKeyStoreProvider>) methods will be ignored. This function can be called more than once. This does shallow copying of the dictionary so that the app cannot alter the custom provider list once it has been set.

ResetStatistics()

If statistics gathering is enabled, all values are reset to zero.

RetrieveInternalInfo()

Returns a name value pair collection of internal properties at the point in time the method is called.

RetrieveStatistics()

Returns a name value pair collection of statistics at the point in time the method is called.

Events

InfoMessage

Occurs when SQL Server returns a warning or informational message.

Explicit Interface Implementations

ICloneable.Clone()

Creates a new object that is a copy of the current instance.

Applies to