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

public ref class OleDbCommand sealed : System::Data::Common::DbCommand, ICloneable, IDisposable
public sealed class OleDbCommand : System.Data.Common.DbCommand, ICloneable, IDisposable
type OleDbCommand = class
    inherit DbCommand
    interface ICloneable
    interface IDbCommand
    interface IDisposable
Public NotInheritable Class OleDbCommand
Inherits DbCommand
Implements ICloneable, IDisposable
Herencia
Implementaciones

Ejemplos

En el ejemplo siguiente se usa el OleDbCommand, junto OleDbDataAdapter y OleDbConnection, para seleccionar las filas de una base de datos de Access.The following example uses the OleDbCommand, along OleDbDataAdapter and OleDbConnection, to select rows from an Access database. El relleno DataSet , a continuación, se devuelve.The filled DataSet is then returned. El ejemplo se pasa un inicializado DataSet, una cadena de conexión, una cadena de consulta que es una instrucción SELECT de SQL y una cadena que es el nombre de la tabla de base de datos de origen.The example is passed an initialized DataSet, a connection string, a query string that is an SQL SELECT statement, and a string that is the name of the source database table.

public void ReadMyData(string connectionString)
{
    string queryString = "SELECT OrderID, CustomerID FROM Orders";
    using (OleDbConnection connection = new OleDbConnection(connectionString))
    {
        OleDbCommand command = new OleDbCommand(queryString, connection);
        connection.Open();
        OleDbDataReader reader = command.ExecuteReader();

        while (reader.Read())
        {
            Console.WriteLine(reader.GetInt32(0) + ", " + reader.GetString(1));
        }
        // always call Close when done reading.
        reader.Close();
    }
}
Public Sub ReadMyData(ByVal connectionString As String)
    Dim queryString As String = "SELECT OrderID, CustomerID FROM Orders"
    Using connection As New OleDbConnection(connectionString)
        Dim command As New OleDbCommand(queryString, connection)

        connection.Open()

        Dim reader As OleDbDataReader = command.ExecuteReader()
        While reader.Read()
            Console.WriteLine(reader.GetInt32(0).ToString() + ", " _
               + reader.GetString(1))
        End While

        ' always call Close when done reading.
        reader.Close()
    End Using
End Sub

Comentarios

Cuando una instancia de OleDbCommand se crea, la lectura y escritura se establecen propiedades en sus valores iniciales.When an instance of OleDbCommand is created, the read/write properties are set to their initial values. Para obtener una lista de estos valores, vea el OleDbCommand constructor.For a list of these values, see the OleDbCommand constructor.

OleDbCommand características de los siguientes métodos de ejecución de comandos en un origen de datos:OleDbCommand features the following methods executing commands at a data source:

ElementoItem DescripciónDescription
ExecuteReader Ejecuta comandos que devuelven filas.Executes commands that return rows. ExecuteReader no se puede tener el efecto deseado si se utiliza para ejecutar comandos como instrucciones SET de SQL.ExecuteReader may not have the effect that you want if used to execute commands such as SQL SET statements.
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 OleDbCommand objeto.You can reset the CommandText property and reuse the OleDbCommand object. Sin embargo, debe cerrar la OleDbDataReader antes de poder ejecutar un comando nuevo o anterior.However, you must close the OleDbDataReader before you can execute a new or previous command.

Si un grave OleDbException (por ejemplo, un SQL Server nivel de gravedad de 20 o superior) generado por el método que ejecuta un OleDbCommand, OleDbConnection, se puede cerrar la conexión.If a fatal OleDbException (for example, a SQL Server severity level of 20 or greater) is generated by the method executing an OleDbCommand, the OleDbConnection, the connection may be closed. Sin embargo, el usuario puede volver a abrir la conexión y continuar.However, the user can reopen the connection and continue.

Constructores

OleDbCommand() OleDbCommand() OleDbCommand() OleDbCommand()

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

OleDbCommand(String) OleDbCommand(String) OleDbCommand(String) OleDbCommand(String)

Inicializa una nueva instancia de la clase OleDbCommand con el texto de la consulta.Initializes a new instance of the OleDbCommand class with the text of the query.

OleDbCommand(String, OleDbConnection) OleDbCommand(String, OleDbConnection) OleDbCommand(String, OleDbConnection) OleDbCommand(String, OleDbConnection)

Inicializa una nueva instancia de la clase OleDbCommand con el texto de la consulta y una OleDbConnection.Initializes a new instance of the OleDbCommand class with the text of the query and an OleDbConnection.

OleDbCommand(String, OleDbConnection, OleDbTransaction) OleDbCommand(String, OleDbConnection, OleDbTransaction) OleDbCommand(String, OleDbConnection, OleDbTransaction) OleDbCommand(String, OleDbConnection, OleDbTransaction)

Inicializa una nueva instancia de la clase OleDbCommand con el texto de la consulta, un objeto OleDbConnection y el objeto Transaction.Initializes a new instance of the OleDbCommand class with the text of the query, an OleDbConnection, 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 la instrucción SQL o procedimiento almacenado que se ejecutan en el origen de datos.Gets or sets the SQL statement or stored procedure to execute at 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 OleDbConnection que usa esta instancia de OleDbCommand.Gets or sets the OleDbConnection used by this instance of the OleDbCommand.

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 personalizado del Diseñador de Windows Forms.Gets or sets a value that indicates whether the command object should be visible in a customized Windows Forms Designer 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 OleDbParameterCollection.Gets the OleDbParameterCollection.

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 OleDbTransaction en la que se ejecuta OleDbCommand.Gets or sets the OleDbTransaction within which the OleDbCommand executes.

UpdatedRowSource UpdatedRowSource UpdatedRowSource UpdatedRowSource

Obtiene o establece cómo se aplican los resultados del comando a la DataRow cuando lo utiliza el Update método de la OleDbDataAdapter.Gets or sets how command results are applied to the DataRow when used by the Update method of the OleDbDataAdapter.

Métodos

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

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

Clone() Clone() Clone() Clone()

Crea un nuevo objeto OleDbCommand que es una copia de la instancia actual.Creates a new OleDbCommand object that is a copy of the current instance.

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 OleDbParameter.Creates a new instance of an OleDbParameter 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 OleDbDataReader.Sends the CommandText to the Connection and builds an OleDbDataReader.

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

Envía el CommandText a la Connectiony genera un OleDbDataReader mediante uno de los CommandBehavior valores.Sends the CommandText to the Connection, and builds an OleDbDataReader 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 on 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()

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

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

Para una descripción de este miembro, vea ExecuteReader().For a description of this member, see ExecuteReader().

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

Ejecuta CommandText contra Connection y genera IDataReader mediante uno de los valores de CommandBehavior.Executes the CommandText against the Connection, and builds an IDataReader using one of the CommandBehavior values.

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: