This documentation is archived and is not being maintained.

SqlCommand.Connection Property

Gets or sets the SqlConnection used by this instance of the SqlCommand.

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

public SqlConnection Connection { get; set; 
/** @property */
public SqlConnection get_Connection ()

/** @property */
public void set_Connection (SqlConnection value)

public function get Connection () : SqlConnection

public function set Connection (value : SqlConnection)

Property Value

The connection to a data source. The default value is a null reference (Nothing in Visual Basic).

Exception typeCondition

InvalidOperationException

The Connection property was changed while a transaction was in progress.

If you set Connection while a transaction is in progress and the Transaction property is not null, an InvalidOperationException is generated. If the Transaction property is not null and the transaction has already been committed or rolled back, Transaction is set to null.

The following example creates a SqlCommand and sets some of its properties.

private static void CreateCommand(string queryString,
    string connectionString)
{
    using (SqlConnection connection = new SqlConnection(
               connectionString))
    {
        SqlCommand command = new SqlCommand();
        command.Connection = connection;
        command.CommandTimeout = 15;
        command.CommandType = CommandType.Text;
        command.CommandText = queryString;

        connection.Open();
        SqlDataReader reader = command.ExecuteReader();
        while (reader.Read())
        {
            Console.WriteLine(String.Format("{0, {1",
                reader[0], reader[1]));
        
    


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
Show: