Export (0) Print
Expand All

SqlConnection.Close Method

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

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

public override void Close ()
public void Close ()
public override function Close ()

Exception typeCondition

SqlException

The connection-level error that occurred while opening the connection.

The Close method rolls back any pending transactions. It then releases the connection to the connection pool, or closes the connection if connection pooling is disabled.

NoteNote

Pending transactions started using Transact-SQL or BeginTransaction are automatically rolled back. Transactions started through System.Transactions are controlled through the System.Transactions infrastructure, and are not affected by SqlConnection.Close.

An application can call Close more than one time. No exception is generated.

If the SqlConnection goes out of scope, it is not closed. Therefore, unless you have placed your code inside of a using statement, you must explicitly close the connection by calling Close or Dispose. They are functionally equivalent. If the connection pooling value Pooling is set to true or yes, this also releases the physical connection.

Caution noteCaution

Do not call Close or Dispose on a Connection, a DataReader, or any other managed object in the Finalize method of your class. In a finalizer, you should only release unmanaged resources that your class owns directly. If your class does not own any unmanaged resources, do not include a Finalize method in your class definition. For more information, see Garbage Collection.

The following example creates a SqlConnection, opens it, displays some of its properties. The connection is automatically closed at the end of the using block.

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


Windows 98, Windows 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 .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.

.NET Framework

Supported in: 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 2.0, 1.0

Community Additions

ADD
Show:
© 2014 Microsoft