OracleCommand Classe

Definição

Cuidado

OracleCommand has been deprecated. http://go.microsoft.com/fwlink/?LinkID=144260

Representa uma instrução SQL ou procedimento armazenado para execução em um banco de dados.Represents an SQL statement or stored procedure to execute against a database. Essa classe não pode ser herdada.This class cannot be inherited.

public ref class OracleCommand sealed : System::ComponentModel::Component, ICloneable, IDisposable, System::Data::IDbCommand
public ref class OracleCommand sealed : System::Data::Common::DbCommand, ICloneable
public sealed class OracleCommand : System.ComponentModel.Component, ICloneable, IDisposable, System.Data.IDbCommand
public sealed class OracleCommand : System.Data.Common.DbCommand, ICloneable
[System.Obsolete("OracleCommand has been deprecated. http://go.microsoft.com/fwlink/?LinkID=144260", false)]
public sealed class OracleCommand : System.Data.Common.DbCommand, ICloneable
type OracleCommand = class
    inherit Component
    interface ICloneable
    interface IDbCommand
    interface IDisposable
type OracleCommand = class
    inherit DbCommand
    interface ICloneable
[<System.Obsolete("OracleCommand has been deprecated. http://go.microsoft.com/fwlink/?LinkID=144260", false)>]
type OracleCommand = class
    inherit DbCommand
    interface ICloneable
Public NotInheritable Class OracleCommand
Inherits Component
Implements ICloneable, IDbCommand, IDisposable
Public NotInheritable Class OracleCommand
Inherits DbCommand
Implements ICloneable
Herança
Herança
Atributos
Implementações

Exemplos

O exemplo a seguir usa o ExecuteReader método de OracleCommand , juntamente com OracleDataReader e OracleConnection , para selecionar linhas de uma tabela.The following example uses the ExecuteReader method of OracleCommand, along with OracleDataReader and OracleConnection, to select rows from a table.

public void ReadMyData(string connectionString)
{
    string queryString = "SELECT EmpNo, DeptNo FROM Scott.Emp";
    using (OracleConnection connection = new OracleConnection(connectionString))
    {
        OracleCommand command = new OracleCommand(queryString, connection);
        connection.Open();
        OracleDataReader reader = command.ExecuteReader();
        try
        {
            while (reader.Read())
            {
                Console.WriteLine(reader.GetInt32(0) + ", " + reader.GetInt32(1));
            }
        }
        finally
        {
            // always call Close when done reading.
            reader.Close();
        }
    }
}
Public Sub ReadMyData(ByVal connectionString As String)
    Dim queryString As String = "SELECT EmpNo, DeptNo FROM Scott.Emp"
    Using connection As New OracleConnection(connectionString)
        Dim command As New OracleCommand(queryString, connection)
        connection.Open()
        Dim reader As OracleDataReader = command.ExecuteReader()
        Try
            While reader.Read()
                Console.WriteLine(reader.GetInt32(0) & ", " _
                   & reader.GetInt32(1))
            End While
        Finally
            ' always call Close when done reading.
            reader.Close()
        End Try
    End Using
End Sub

Comentários

Esse tipo foi preterido e será removido em uma versão futura do .NET Framework.This type is deprecated and will be removed in a future version of the .NET Framework. Para obter mais informações, consulte Oracle e ADO.net.For more information, see Oracle and ADO.NET.

A OracleCommand classe fornece os seguintes métodos para executar comandos em uma fonte de dados:The OracleCommand class provides the following methods for executing commands against a data source:

ItemItem DescriçãoDescription
ExecuteReader Executa comandos que retornam linhas.Executes commands that return rows.
ExecuteOracleNonQuery Executa uma instrução SQL no Connection e retorna o número de linhas afetadas.Executes an SQL statement against the Connection and returns the number of rows affected.
ExecuteNonQuery Executa comandos como instruções SQL INSERT, DELETE, UPDATE e SET.Executes commands such as SQL INSERT, DELETE, UPDATE, and SET statements.
ExecuteScalar Recupera um único valor (por exemplo, um valor de agregação) de um banco de dados como um tipo .NET Framework.Retrieves a single value (for example, an aggregate value) from a database as a .NET Framework data type.
ExecuteOracleScalar Recupera um único valor (por exemplo, um valor de agregação) de um banco de dados como um tipo de dado específico da Oracle.Retrieves a single value (for example, an aggregate value) from a database as an Oracle-specific data type.

Você pode redefinir a CommandText propriedade e reutilizar o OracleCommand objeto.You can reset the CommandText property and reuse the OracleCommand object.

Se a execução do comando resultar em um fatal OracleException , o OracleConnection poderá fechar.If execution of the command results in a fatal OracleException, the OracleConnection may close. No entanto, o usuário pode reabrir a conexão e continuar.However, the user can reopen the connection and continue.

Observação

Ao contrário do objeto de comando nos outros provedores de dados de .NET Framework (SQL Server, OLE DB e ODBC), o OracleCommand objeto não oferece suporte a uma CommandTimeout propriedade.Unlike the Command object in the other .NET Framework data providers (SQL Server, OLE DB, and ODBC), the OracleCommand object does not support a CommandTimeout property. Definir um tempo limite de comando não tem nenhum efeito e o valor retornado é sempre zero.Setting a command timeout has no effect and the value returned is always zero.

Construtores

OracleCommand()

Inicializa uma nova instância do OracleCommand.Initializes a new instance of the OracleCommand.

OracleCommand(String)

Inicializa uma nova instância da classe OracleCommand com o texto da consulta.Initializes a new instance of the OracleCommand class with the text of the query.

OracleCommand(String, OracleConnection)

Inicializa uma nova instância da classe OracleCommand com o texto da consulta e um objeto OracleConnection.Initializes a new instance of the OracleCommand class with the text of the query and an OracleConnection object.

OracleCommand(String, OracleConnection, OracleTransaction)

Inicializa uma nova instância da classe OracleCommand com o texto da consulta, um objeto OracleConnection e um OracleTransaction.Initializes a new instance of the OracleCommand class with the text of the query, an OracleConnection object, and an OracleTransaction.

Propriedades

CanRaiseEvents

Obtém um valor que indica se o componente pode acionar um evento.Gets a value indicating whether the component can raise an event.

(Herdado de Component)
CommandText

Obtém ou define a instrução SQL ou o procedimento armazenado a ser executado no banco de dados.Gets or sets the SQL statement or stored procedure to execute against the database.

CommandTimeout

Obtém ou define o tempo de espera (em segundos) antes de encerrar a tentativa de executar um comando e antes de gerar um erro.Gets or sets the wait time (in seconds) before terminating the attempt to execute a command and generating an error.

CommandType

Obtém ou define um valor que indica como a propriedade CommandText é interpretada.Gets or sets a value indicating how the CommandText property is interpreted.

Connection

Obtém ou define o OracleConnection usado por essa instância do OracleCommand.Gets or sets the OracleConnection used by this instance of the OracleCommand.

Container

Obtém o IContainer que contém o Component.Gets the IContainer that contains the Component.

(Herdado de Component)
DbConnection

Quando substituído em uma classe derivada, obtém ou define o DbConnection usado por este DbCommand.When overridden in a derived class, gets or sets the DbConnection used by this DbCommand.

(Herdado de DbCommand)
DbParameterCollection

Quando substituído em uma classe derivada, obtém a coleção de objetos DbParameter.When overridden in a derived class, gets the collection of DbParameter objects.

(Herdado de DbCommand)
DbTransaction

Quando substituído em uma classe derivada, obtém ou define o DbTransaction dentro do qual este objeto DbCommand é executado.When overridden in a derived class, gets or sets the DbTransaction within which this DbCommand object executes.

(Herdado de DbCommand)
DesignMode

Obtém um valor que indica se o Component está no modo de design no momento.Gets a value that indicates whether the Component is currently in design mode.

(Herdado de Component)
DesignTimeVisible

Obtém ou define um valor que indica se o objeto de comando deve estar visível em um controle da interface personalizada.Gets or sets a value indicating whether the command object should be visible in a customized interface control.

Events

Obtém a lista de manipuladores de eventos que estão anexados a este Component.Gets the list of event handlers that are attached to this Component.

(Herdado de Component)
Parameters

Obtém o OracleParameterCollection.Gets the OracleParameterCollection.

Site

Obtém ou define o ISite do Component.Gets or sets the ISite of the Component.

(Herdado de Component)
Transaction

Obtém ou define o OracleCommand em que o OracleTransaction é executado.Gets or sets the OracleTransaction within which the OracleCommand executes.

UpdatedRowSource

Obtém ou define um valor que especifica como o método Update deve aplicar os resultados do comando ao DataRow.Gets or sets a value that specifies how the Update method should apply command results to the DataRow.

Métodos

Cancel()

Tenta cancelar a execução de um OracleCommand.Attempts to cancel the execution of an OracleCommand.

Clone()

Cria uma cópia deste objeto OracleCommand.Creates a copy of this OracleCommand object.

CreateDbParameter()

Quando substituído em uma classe derivada, cria uma nova instância de um objeto DbParameter.When overridden in a derived class, creates a new instance of a DbParameter object.

(Herdado de DbCommand)
CreateObjRef(Type)

Cria um objeto que contém todas as informações relevantes necessárias para gerar um proxy usado para se comunicar com um objeto remoto.Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Herdado de MarshalByRefObject)
CreateParameter()

Cria uma nova instância de um objeto OracleParameter.Creates a new instance of an OracleParameter object.

Dispose()

Libera todos os recursos usados pelo Component.Releases all resources used by the Component.

(Herdado de Component)
Dispose()

Realiza tarefas definidas pelo aplicativo associadas à liberação ou à redefinição de recursos não gerenciados.Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.

(Herdado de DbCommand)
Dispose(Boolean)

Libera os recursos não gerenciados usados pelo Component e opcionalmente libera os recursos gerenciados.Releases the unmanaged resources used by the Component and optionally releases the managed resources.

(Herdado de Component)
Dispose(Boolean)

Libera os recursos não gerenciados usados pelo DbCommand e opcionalmente libera os recursos gerenciados.Releases the unmanaged resources used by the DbCommand and optionally releases the managed resources.

(Herdado de DbCommand)
DisposeAsync()

Descarta de forma assíncrona o objeto de comando.Asynchronously diposes the command object.

(Herdado de DbCommand)
Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object.

(Herdado de Object)
ExecuteDbDataReader(CommandBehavior)

Quando substituído em uma classe derivada, executa o texto de comando em relação à conexão.When overridden in a derived class, executes the command text against the connection.

(Herdado de DbCommand)
ExecuteDbDataReaderAsync(CommandBehavior, CancellationToken)

Os provedores devem implementar esse método para fornecer uma implementação não padrão para sobrecargas ExecuteReader.Providers should implement this method to provide a non-default implementation for ExecuteReader overloads.

A implementação padrão invoca o método ExecuteReader() síncrono e retorna uma tarefa concluída, bloqueando o thread de chamada.The default implementation invokes the synchronous ExecuteReader() method and returns a completed task, blocking the calling thread. A implementação padrão retornará uma tarefa cancelada se já tiver passado um token de cancelamento.The default implementation will return a cancelled task if passed an already cancelled cancellation token. Exceções geradas por ExecuteReader serão comunicadas por meio da propriedade Exceção de Tarefa retornada.Exceptions thrown by ExecuteReader will be communicated via the returned Task Exception property.

Esse método aceita um token de cancelamento que pode ser usado para solicitar a operação a ser cancelada no início.This method accepts a cancellation token that can be used to request the operation to be cancelled early. As implementações podem ignorar essa solicitação.Implementations may ignore this request.

(Herdado de DbCommand)
ExecuteNonQuery()

Executa uma instrução SQL no Connection e retorna o número de linhas afetadas.Executes an SQL statement against the Connection and returns the number of rows affected.

ExecuteNonQueryAsync()

Uma versão assíncrona de ExecuteNonQuery(), que executa uma instrução SQL em um objeto de conexão.An asynchronous version of ExecuteNonQuery(), which executes a SQL statement against a connection object.

Invoca ExecuteNonQueryAsync(CancellationToken) com CancellationToken.None.Invokes ExecuteNonQueryAsync(CancellationToken) with CancellationToken.None.

(Herdado de DbCommand)
ExecuteNonQueryAsync(CancellationToken)

Essa é a versão assíncrona de ExecuteNonQuery().This is the asynchronous version of ExecuteNonQuery(). Provedores devem substituir com uma implementação apropriada.Providers should override with an appropriate implementation. Opcionalmente, o token de cancelamento pode ser ignorado.The cancellation token may optionally be ignored.

A implementação padrão invoca o método ExecuteNonQuery() síncrono e retorna uma tarefa concluída, bloqueando o thread de chamada.The default implementation invokes the synchronous ExecuteNonQuery() method and returns a completed task, blocking the calling thread. A implementação padrão retornará uma tarefa cancelada se já tiver passado um token de cancelamento.The default implementation will return a cancelled task if passed an already cancelled cancellation token. Exceções geradas por ExecuteNonQuery() serão comunicadas por meio da propriedade Exceção de Tarefa retornada.Exceptions thrown by ExecuteNonQuery() will be communicated via the returned Task Exception property.

Não invoque outros métodos e propriedades do objeto DbCommand até a Tarefa retornada ser concluída.Do not invoke other methods and properties of the DbCommand object until the returned Task is complete.

(Herdado de DbCommand)
ExecuteOracleNonQuery(OracleString)

Executa uma instrução SQL no Connection e retorna o número de linhas afetadas.Executes an SQL statement against the Connection and returns the number of rows affected.

ExecuteOracleScalar()

Executa a consulta e retorna a primeira coluna da primeira linha do conjunto de resultados retornado pela consulta como um tipo de dados específico do Oracle.Executes the query, and returns the first column of the first row in the result set returned by the query as an Oracle-specific data type. Colunas ou linhas extra são ignoradas.Extra columns or rows are ignored.

ExecuteReader()

Envia o CommandText para o Connection e cria um OracleDataReader.Sends the CommandText to the Connection and builds an OracleDataReader.

ExecuteReader(CommandBehavior)

Envia o CommandText para o Connection e cria um OracleDataReader usando um dos valores CommandBehavior.Sends the CommandText to the Connection, and builds an OracleDataReader using one of the CommandBehavior values.

ExecuteReaderAsync()

Uma versão assíncrona de ExecuteReader, que executa o CommandText contra o Connection e retorna um DbDataReader.An asynchronous version of ExecuteReader, which executes the CommandText against the Connection and returns a DbDataReader.

Invoca ExecuteDbDataReaderAsync(CommandBehavior, CancellationToken) com CancellationToken.None.Invokes ExecuteDbDataReaderAsync(CommandBehavior, CancellationToken) with CancellationToken.None.

(Herdado de DbCommand)
ExecuteReaderAsync(CancellationToken)

Uma versão assíncrona de ExecuteReader, que executa o CommandText contra o Connection e retorna um DbDataReader.An asynchronous version of ExecuteReader, which executes the CommandText against the Connection and returns a DbDataReader. Esse método propaga a notificação de que as operações devem ser canceladas.This method propagates a notification that operations should be canceled.

Invoca ExecuteDbDataReaderAsync(CommandBehavior, CancellationToken).Invokes ExecuteDbDataReaderAsync(CommandBehavior, CancellationToken).

(Herdado de DbCommand)
ExecuteReaderAsync(CommandBehavior)

Uma versão assíncrona de ExecuteReader, que executa o CommandText contra o Connection e retorna um DbDataReader.An asynchronous version of ExecuteReader, which executes the CommandText against the Connection and returns a DbDataReader.

Invoca ExecuteDbDataReaderAsync(CommandBehavior, CancellationToken).Invokes ExecuteDbDataReaderAsync(CommandBehavior, CancellationToken).

(Herdado de DbCommand)
ExecuteReaderAsync(CommandBehavior, CancellationToken)

Invoca ExecuteDbDataReaderAsync(CommandBehavior, CancellationToken).Invokes ExecuteDbDataReaderAsync(CommandBehavior, CancellationToken).

(Herdado de DbCommand)
ExecuteScalar()

Executa a consulta e retorna a primeira coluna da primeira linha do conjunto de resultados retornado pela consulta como um tipo de dados do .NET.Executes the query, and returns the first column of the first row in the result set returned by the query as a .NET data type. Colunas ou linhas extra são ignoradas.Extra columns or rows are ignored.

ExecuteScalarAsync()

Uma versão assíncrona de ExecuteScalar(), que executa a consulta e retorna a primeira coluna da primeira linha no conjunto de resultados retornado pela consulta.An asynchronous version of ExecuteScalar(), which executes the query and returns the first column of the first row in the result set returned by the query. Todas as outras colunas e linhas são ignoradas.All other columns and rows are ignored.

Invoca ExecuteScalarAsync(CancellationToken) com CancellationToken.None.Invokes ExecuteScalarAsync(CancellationToken) with CancellationToken.None.

(Herdado de DbCommand)
ExecuteScalarAsync(CancellationToken)

Essa é a versão assíncrona de ExecuteScalar().This is the asynchronous version of ExecuteScalar(). Provedores devem substituir com uma implementação apropriada.Providers should override with an appropriate implementation. Opcionalmente, o token de cancelamento pode ser ignorado.The cancellation token may optionally be ignored.

A implementação padrão invoca o método ExecuteScalar() síncrono e retorna uma tarefa concluída, bloqueando o thread de chamada.The default implementation invokes the synchronous ExecuteScalar() method and returns a completed task, blocking the calling thread. A implementação padrão retornará uma tarefa cancelada se já tiver passado um token de cancelamento.The default implementation will return a cancelled task if passed an already cancelled cancellation token. Exceções geradas por ExecuteScalar serão comunicadas por meio da propriedade Exceção de Tarefa retornada.Exceptions thrown by ExecuteScalar will be communicated via the returned Task Exception property.

Não invoque outros métodos e propriedades do objeto DbCommand até a Tarefa retornada ser concluída.Do not invoke other methods and properties of the DbCommand object until the returned Task is complete.

(Herdado de DbCommand)
GetHashCode()

Serve como a função de hash padrão.Serves as the default hash function.

(Herdado de Object)
GetLifetimeService()
Obsoleto.

Recupera o objeto de serviço de tempo de vida atual que controla a política de ciclo de vida para esta instância.Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Herdado de MarshalByRefObject)
GetService(Type)

Retorna um objeto que representa um serviço fornecido pelo Component ou pelo seu Container.Returns an object that represents a service provided by the Component or by its Container.

(Herdado de Component)
GetType()

Obtém o Type da instância atual.Gets the Type of the current instance.

(Herdado de Object)
InitializeLifetimeService()
Obsoleto.

Obtém um objeto de serviço de tempo de vida para controlar a política de tempo de vida para essa instância.Obtains a lifetime service object to control the lifetime policy for this instance.

(Herdado de MarshalByRefObject)
MemberwiseClone()

Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object.

(Herdado de Object)
MemberwiseClone(Boolean)

Cria uma cópia superficial do objeto MarshalByRefObject atual.Creates a shallow copy of the current MarshalByRefObject object.

(Herdado de MarshalByRefObject)
Prepare()

Cria uma versão preparada (ou compilada) do comando na fonte de dados.Creates a prepared (or compiled) version of the command at the data source.

PrepareAsync(CancellationToken)

Cria de maneira assíncrona uma versão preparada (ou compilada) do comando na fonte de dados.Asynchronously creates a prepared (or compiled) version of the command on the data source.

(Herdado de DbCommand)
ResetCommandTimeout()

Redefine a propriedade CommandTimeout para o valor padrão.Resets the CommandTimeout property to the default value.

ToString()

Retorna um String que contém o nome do Component, se houver.Returns a String containing the name of the Component, if any. Esse método não deve ser substituído.This method should not be overridden.

(Herdado de Component)

Eventos

Disposed

Ocorre quando o componente é disposto por uma chamada ao método Dispose().Occurs when the component is disposed by a call to the Dispose() method.

(Herdado de Component)

Implantações explícitas de interface

IDbCommand.Connection

Obtém ou define o IDbConnection usado por essa instância do IDbCommand.Gets or sets the IDbConnection used by this instance of the IDbCommand.

(Herdado de DbCommand)
IDbCommand.CreateParameter()

Cria uma nova instância de um objeto IDbDataParameter.Creates a new instance of an IDbDataParameter object.

IDbCommand.CreateParameter()

Cria uma nova instância de um objeto IDbDataParameter.Creates a new instance of an IDbDataParameter object.

(Herdado de DbCommand)
IDbCommand.ExecuteReader()

Executa o CommandText no Connection e compila um IDataReader.Executes the CommandText against the Connection and builds an IDataReader.

IDbCommand.ExecuteReader()

Executa o CommandText no Connection e compila um IDataReader.Executes the CommandText against the Connection and builds an IDataReader.

(Herdado de DbCommand)
IDbCommand.ExecuteReader(CommandBehavior)

Executa o CommandText na conexão Connection e cria um IDataReader usando um dos valores de CommandBehavior.Executes the CommandText against the Connection, and builds an IDataReader by using one of the CommandBehavior values.

IDbCommand.ExecuteReader(CommandBehavior)

Executa o CommandText para o Connection e cria um IDataReader usando um dos valores de CommandBehavior.Executes the CommandText against the Connection, and builds an IDataReader using one of the CommandBehavior values.

(Herdado de DbCommand)
IDbCommand.Parameters

Obtém o IDataParameterCollection.Gets the IDataParameterCollection.

(Herdado de DbCommand)
IDbCommand.Transaction

Obtém ou define o DbCommand em que este objeto DbTransaction é executado.Gets or sets the DbTransaction within which this DbCommand object executes.

(Herdado de DbCommand)

Aplica-se a