SqlCommand.Connection Propriedade

Definição

Obtém ou define o SqlConnection usado por esta instância do SqlCommand.

public:
 property System::Data::SqlClient::SqlConnection ^ Connection { System::Data::SqlClient::SqlConnection ^ get(); void set(System::Data::SqlClient::SqlConnection ^ value); };
[System.Data.DataSysDescription("DbCommand_Connection")]
public System.Data.SqlClient.SqlConnection Connection { get; set; }
public System.Data.SqlClient.SqlConnection Connection { get; set; }
[<System.Data.DataSysDescription("DbCommand_Connection")>]
member this.Connection : System.Data.SqlClient.SqlConnection with get, set
member this.Connection : System.Data.SqlClient.SqlConnection with get, set
Public Property Connection As SqlConnection

Valor de Propriedade

A ligação a uma fonte de dados. O valor predefinido é null.

Atributos

Exceções

A Connection propriedade foi alterada enquanto o comando foi recrutado numa transação.

Exemplos

O exemplo seguinte cria um SqlCommand e define algumas das suas propriedades.

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]));
        }
    }
}
Public Sub CreateCommand(ByVal queryString As String, _
  ByVal connectionString As String)
    Using connection As New SqlConnection(connectionString)
        Dim command As New SqlCommand()
        command.Connection = connection
        command.CommandTimeout = 15
        command.CommandType = CommandType.Text
        command.CommandText = queryString

        connection.Open()
        Dim reader As SqlDataReader = command.ExecuteReader()
            While reader.Read()
            Console.WriteLine(String.Format("{0}, {1}", _
                reader(0), reader(1)))
        End While
    End Using
End Sub

Observações

Se o comando estiver registado numa transação existente e a ligação for alterada, tentar executar o comando gerará um InvalidOperationException.

Se a Transaction propriedade não for nula e a transação já tiver sido comprometida ou revertida, Transaction é definida como nula.

Aplica-se a

Ver também