SqlCommand.Connection SqlCommand.Connection SqlCommand.Connection SqlCommand.Connection Property

定义

获取或设置 SqlCommand 的此实例使用的 SqlConnectionGets or sets the SqlConnection used by this instance of the 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; }
member this.Connection : System.Data.SqlClient.SqlConnection with get, set
Public Property Connection As SqlConnection

属性值

到数据源的连接。The connection to a data source. 默认值为 nullThe default value is null.

异常

命令在事务中登记时 Connection 属性被更改。The Connection property was changed while the command was enlisted in a transaction.

示例

下面的示例创建SqlCommand并设置其一些属性。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]));
        }
    }
}
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

注解

如果命令在现有事务中登记并且连接已更改,则尝试执行命令将引发InvalidOperationExceptionIf the command is enlisted in an existing transaction, and the connection is changed, trying to execute the command will throw an InvalidOperationException.

如果 Transaction 属性不为 null,而事务已提交或回滚,则会将 Transaction 设置为 null。If the Transaction property is not null and the transaction has already been committed or rolled back, Transaction is set to null.

适用于

另请参阅