OdbcCommand OdbcCommand OdbcCommand OdbcCommand Class

Definição

Representa uma instrução SQL ou procedimento armazenado a executar contra uma fonte de dados.Represents an SQL statement or stored procedure to execute against a data source. Essa classe não pode ser herdada.This class cannot be inherited.

public ref class OdbcCommand sealed : System::Data::Common::DbCommand, ICloneable
public sealed class OdbcCommand : System.Data.Common.DbCommand, ICloneable
type OdbcCommand = class
    inherit DbCommand
    interface ICloneable
Public NotInheritable Class OdbcCommand
Inherits DbCommand
Implements ICloneable
Herança
Implementações

Exemplos

O exemplo a seguir ExecuteNonQueryusa.The following example uses ExecuteNonQuery.

public void InsertRow(string connectionString, string insertSQL)
{
    using (OdbcConnection connection = 
               new OdbcConnection(connectionString))
    {
        // The insertSQL string contains a SQL statement that
        // inserts a new row in the source table.
        OdbcCommand command = new OdbcCommand(insertSQL, connection);

        // Open the connection and execute the insert command.
        try
        {
            connection.Open();
            command.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        // The connection is automatically closed when the
        // code exits the using block.
    }
Public Sub InsertRow(ByVal connectionString As String, _
    ByVal insertSQL As String)

    Using connection As New OdbcConnection(connectionString)
        ' The insertSQL string contains a SQL statement that
        ' inserts a new row in the source table.
        Dim command As New OdbcCommand(insertSQL, connection)

        ' Open the connection and execute the insert command.
        Try
            connection.Open()
            command.ExecuteNonQuery()
        Catch ex As Exception
            Console.WriteLine(ex.Message)
        End Try
        ' The connection is automatically closed when the
        ' code exits the Using block.
    End Using
End Sub

Comentários

A OdbcCommand classe fornece os seguintes métodos para executar comandos em uma fonte de dados:The OdbcCommand 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.
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.Retrieves a single value, for example, an aggregate value, from a database.

Você pode redefinir a CommandText Propriedade e reutilizar OdbcCommand o objeto.You can reset the CommandText property and reuse the OdbcCommand object. No entanto, você deve OdbcDataReader fechar o antes de executar um comando novo ou anterior.However, you must close the OdbcDataReader before you can execute a new or previous command.

Se a execução do comando causar um fatal OdbcException , como um nível de severidade de SQL Server de 20 ou OdbcConnection mais, poderá fechar.If execution of the command causes a fatal OdbcException such as a SQL Server severity level of 20 or more, OdbcConnection may close. No entanto, o usuário pode reabrir a conexão e continuar.However, the user can reopen the connection and continue.

Construtores

OdbcCommand() OdbcCommand() OdbcCommand() OdbcCommand()

Inicializa uma nova instância da classe OdbcCommand.Initializes a new instance of the OdbcCommand class.

OdbcCommand(String) OdbcCommand(String) OdbcCommand(String) OdbcCommand(String)

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

OdbcCommand(String, OdbcConnection) OdbcCommand(String, OdbcConnection) OdbcCommand(String, OdbcConnection) OdbcCommand(String, OdbcConnection)

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

OdbcCommand(String, OdbcConnection, OdbcTransaction) OdbcCommand(String, OdbcConnection, OdbcTransaction) OdbcCommand(String, OdbcConnection, OdbcTransaction) OdbcCommand(String, OdbcConnection, OdbcTransaction)

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

Propriedades

CanRaiseEvents CanRaiseEvents CanRaiseEvents 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.

(Inherited from Component)
CommandText CommandText CommandText CommandText

Obtém ou define a instrução SQL ou o procedimento armazenado a ser executado em relação à fonte de dados.Gets or sets the SQL statement or stored procedure to execute against the data source.

CommandTimeout CommandTimeout CommandTimeout CommandTimeout

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

CommandType CommandType CommandType CommandType

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

Connection Connection Connection Connection

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

Container Container Container Container

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

(Inherited from Component)
DesignMode DesignMode DesignMode 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.

(Inherited from Component)
DesignTimeVisible DesignTimeVisible DesignTimeVisible 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 that indicates whether the command object should be visible in a customized interface control.

Events Events Events 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.

(Inherited from Component)
Parameters Parameters Parameters Parameters

Obtém o OdbcParameterCollection.Gets the OdbcParameterCollection.

Site Site Site Site

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

(Inherited from Component)
Transaction Transaction Transaction Transaction

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

UpdatedRowSource UpdatedRowSource UpdatedRowSource UpdatedRowSource

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

Métodos

Cancel() Cancel() Cancel() Cancel()

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

CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type) 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.

(Inherited from MarshalByRefObject)
CreateParameter() CreateParameter() CreateParameter() CreateParameter()

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

Dispose() Dispose() Dispose() Dispose()

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

(Inherited from Component)
Dispose(Boolean) Dispose(Boolean) Dispose(Boolean) 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.

(Inherited from Component)
Equals(Object) Equals(Object) Equals(Object) Equals(Object)

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

(Inherited from Object)
ExecuteNonQuery() ExecuteNonQuery() ExecuteNonQuery() 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.

ExecuteReader() ExecuteReader() ExecuteReader() ExecuteReader()

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

ExecuteReader(CommandBehavior) ExecuteReader(CommandBehavior) ExecuteReader(CommandBehavior) ExecuteReader(CommandBehavior)

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

ExecuteScalar() ExecuteScalar() ExecuteScalar() ExecuteScalar()

Executa a consulta e retorna a primeira coluna da primeira linha do conjunto de resultados retornado pela consulta.Executes the query, and returns the first column of the first row in the result set returned by the query. Colunas ou linhas adicionais são ignoradas.Additional columns or rows are ignored.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

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

(Inherited from Object)
GetLifetimeService() GetLifetimeService() GetLifetimeService() GetLifetimeService()

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.

(Inherited from MarshalByRefObject)
GetService(Type) GetService(Type) GetService(Type) 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.

(Inherited from Component)
GetType() GetType() GetType() GetType()

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

(Inherited from Object)
InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService()

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.

(Inherited from MarshalByRefObject)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

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

(Inherited from Object)
MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean)

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

(Inherited from MarshalByRefObject)
Prepare() Prepare() Prepare() 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.

ResetCommandTimeout() ResetCommandTimeout() ResetCommandTimeout() ResetCommandTimeout()

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

ToString() ToString() ToString() 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.

(Inherited from Component)

Implantações explícitas de interface

ICloneable.Clone() ICloneable.Clone() ICloneable.Clone() ICloneable.Clone()

Para obter uma descrição desse membro, consulte Clone().For a description of this member, see Clone().

IDbCommand.CreateParameter() IDbCommand.CreateParameter() IDbCommand.CreateParameter() IDbCommand.CreateParameter()
IDbCommand.ExecuteReader() IDbCommand.ExecuteReader() IDbCommand.ExecuteReader() IDbCommand.ExecuteReader()

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

IDbCommand.ExecuteReader(CommandBehavior) IDbCommand.ExecuteReader(CommandBehavior) IDbCommand.ExecuteReader(CommandBehavior) IDbCommand.ExecuteReader(CommandBehavior)

Executa o CommandText na Connection e cria um IDataReader usando o comportamento especificado.Executes the CommandText against the Connection, and builds an IDataReader using the specified behavior.

Eventos

Disposed Disposed Disposed Disposed

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

(Inherited from Component)

Aplica-se a

Veja também