OdbcCommand OdbcCommand OdbcCommand OdbcCommand Class

Definición

Representa una instrucción SQL o un procedimiento almacenado que se van a ejecutar en un origen de datos.Represents an SQL statement or stored procedure to execute against a data source. Esta clase no puede heredarse.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
Herencia
Implementaciones

Ejemplos

En el ejemplo siguiente se usa ExecuteNonQuery.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

Comentarios

La OdbcCommand clase proporciona los métodos siguientes para ejecutar comandos en un origen de datos:The OdbcCommand class provides the following methods for executing commands against a data source:

ElementoItem DescripciónDescription
ExecuteReader Ejecuta comandos que devuelven filas.Executes commands that return rows.
ExecuteNonQuery Ejecuta comandos como instrucciones SQL INSERT, DELETE, UPDATE y conjunto.Executes commands such as SQL INSERT, DELETE, UPDATE, and SET statements.
ExecuteScalar Recupera un valor único, por ejemplo, un valor agregado de una base de datos.Retrieves a single value, for example, an aggregate value, from a database.

Puede restablecer el CommandText propiedad y volver a utilizar el OdbcCommand objeto.You can reset the CommandText property and reuse the OdbcCommand object. Sin embargo, debe cerrar la OdbcDataReader antes de poder ejecutar un comando nuevo o anterior.However, you must close the OdbcDataReader before you can execute a new or previous command.

Si la ejecución del comando hace que un grave OdbcException como un nivel de gravedad de SQL Server de 20 o más, OdbcConnection puede cerrarse.If execution of the command causes a fatal OdbcException such as a SQL Server severity level of 20 or more, OdbcConnection may close. Sin embargo, el usuario puede volver a abrir la conexión y continuar.However, the user can reopen the connection and continue.

Constructores

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

Inicializa una nueva instancia de la clase OdbcCommand.Initializes a new instance of the OdbcCommand class.

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

Inicializa una nueva instancia de la clase OdbcCommand con el texto de la 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 una nueva instancia de la OdbcCommand clase con el texto de la consulta y un OdbcConnection objeto.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 una nueva instancia de la clase OdbcCommand con el texto de la consulta, un objeto OdbcConnection y Transaction.Initializes a new instance of the OdbcCommand class with the text of the query, an OdbcConnection object, and the Transaction.

Propiedades

CanRaiseEvents CanRaiseEvents CanRaiseEvents CanRaiseEvents

Obtiene un valor que indica si el componente puede generar un evento.Gets a value indicating whether the component can raise an event.

(Inherited from Component)
CommandText CommandText CommandText CommandText

Obtiene o establece una instrucción SQL o un procedimiento almacenado que se van a ejecutar en un origen de datos.Gets or sets the SQL statement or stored procedure to execute against the data source.

CommandTimeout CommandTimeout CommandTimeout CommandTimeout

Obtiene o establece el tiempo de espera antes de detener un intento de ejecutar un comando y generar un error.Gets or sets the wait time before terminating an attempt to execute a command and generating an error.

CommandType CommandType CommandType CommandType

Obtiene o establece un valor que indica cómo se interpreta la propiedad CommandText.Gets or sets a value that indicates how the CommandText property is interpreted.

Connection Connection Connection Connection

Obtiene o establece la interfaz OdbcConnection que usa esta instancia de OdbcCommand.Gets or sets the OdbcConnection used by this instance of the OdbcCommand.

Container Container Container Container

Obtiene IContainer que contiene Component.Gets the IContainer that contains the Component.

(Inherited from Component)
DesignMode DesignMode DesignMode DesignMode

Obtiene un valor que indica si Component está actualmente en modo de diseño.Gets a value that indicates whether the Component is currently in design mode.

(Inherited from Component)
DesignTimeVisible DesignTimeVisible DesignTimeVisible DesignTimeVisible

Obtiene o establece un valor que indica si el objeto de comando debe estar visible en un control de interfaz personalizado.Gets or sets a value that indicates whether the command object should be visible in a customized interface control.

Events Events Events Events

Obtiene la lista de controladores de eventos asociados a Component.Gets the list of event handlers that are attached to this Component.

(Inherited from Component)
Parameters Parameters Parameters Parameters

Obtiene la estructura OdbcParameterCollection.Gets the OdbcParameterCollection.

Site Site Site Site

Obtiene o establece el ISite de Component.Gets or sets the ISite of the Component.

(Inherited from Component)
Transaction Transaction Transaction Transaction

Obtiene o establece la transacción OdbcTransaction en la que se ejecuta OdbcCommand.Gets or sets the OdbcTransaction within which the OdbcCommand executes.

UpdatedRowSource UpdatedRowSource UpdatedRowSource UpdatedRowSource

Obtiene o establece un valor que especifica cómo debe aplicar el método Update los resultados del comando en 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()

Intenta cancelar la ejecución de un OdbcCommand.Tries to cancel the execution of an OdbcCommand.

CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type)

Crea un objeto que contiene toda la información relevante necesaria para generar un proxy utilizado para comunicarse con un 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()

Crea una nueva instancia de un objeto OdbcParameter.Creates a new instance of an OdbcParameter object.

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

Libera todos los recursos que usa Component.Releases all resources used by the Component.

(Inherited from Component)
Dispose(Boolean) Dispose(Boolean) Dispose(Boolean) Dispose(Boolean)

Libera los recursos no administrados que usa Component y, de forma opcional, libera los recursos administrados.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 si el objeto especificado es igual al objeto actual.Determines whether the specified object is equal to the current object.

(Inherited from Object)
ExecuteNonQuery() ExecuteNonQuery() ExecuteNonQuery() ExecuteNonQuery()

Ejecuta una instrucción SQL en el Connection y devuelve el número de filas afectadas.Executes an SQL statement against the Connection and returns the number of rows affected.

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

Envía el CommandText a la Connection y compila un OdbcDataReader.Sends the CommandText to the Connection and builds an OdbcDataReader.

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

Envía el CommandText a la Connectiony genera un OdbcDataReader mediante uno de los CommandBehavior valores.Sends the CommandText to the Connection, and builds an OdbcDataReader using one of the CommandBehavior values.

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

Ejecuta la consulta y devuelve la primera columna de la primera fila del conjunto de resultados devuelto por la consulta.Executes the query, and returns the first column of the first row in the result set returned by the query. Las demás columnas o filas no se tienen en cuenta.Additional columns or rows are ignored.

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

Sirve como la función hash predeterminada.Serves as the default hash function.

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

Recupera el objeto de servicio de duración actual que controla la directiva de duración de esta instancia.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)

Devuelve un objeto que representa el servicio suministrado por Component o por Container.Returns an object that represents a service provided by the Component or by its Container.

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

Obtiene el Type de la instancia actual.Gets the Type of the current instance.

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

Obtiene un objeto de servicio de duración para controlar la directiva de duración de esta instancia.Obtains a lifetime service object to control the lifetime policy for this instance.

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

Crea una copia superficial del Object actual.Creates a shallow copy of the current Object.

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

Crea una copia superficial del objeto MarshalByRefObject actual.Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject)
Prepare() Prepare() Prepare() Prepare()

Crea una versión preparada o compilada del comando en el origen de datos.Creates a prepared or compiled version of the command at the data source.

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

Restablece el CommandTimeout propiedad en el valor predeterminado.Resets the CommandTimeout property to the default value.

ToString() ToString() ToString() ToString()

Devuelve una String que contiene el nombre del Component, si existe.Returns a String containing the name of the Component, if any. Este método no se debe invalidar.This method should not be overridden.

(Inherited from Component)

Implementaciones de interfaz explícitas

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

Para una descripción de este miembro, vea 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()

Ejecuta CommandText contra Connection y genera IDataReader.Executes the CommandText against the Connection and builds an IDataReader.

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

Ejecuta el CommandText contra la Connectiony genera una IDataReader usando el comportamiento especificado.Executes the CommandText against the Connection, and builds an IDataReader using the specified behavior.

Eventos

Disposed Disposed Disposed Disposed

Se produce cuando el componente se elimina mediante una llamada al método Dispose().Occurs when the component is disposed by a call to the Dispose() method.

(Inherited from Component)

Se aplica a

Consulte también: