Sugerir traducción
 
Otros han sugerido:

progress indicator
No hay más sugerencias.
Evaluar y enviar comentarios
Contraer todo/Expandir todo Contraer todo
Ver contenido:  en paraleloVer contenido: en paralelo
.NET Framework Class Library
OleDbCommand Class

Represents an SQL statement or stored procedure to execute against a data source.

System..::.Object
  System..::.MarshalByRefObject
    System.ComponentModel..::.Component
      System.Data.Common..::.DbCommand
        System.Data.OleDb..::.OleDbCommand

Namespace:  System.Data.OleDb
Assembly:  System.Data (in System.Data.dll)
Visual Basic
Public NotInheritable Class OleDbCommand _
    Inherits DbCommand _
    Implements ICloneable, IDbCommand, IDisposable
C#
public sealed class OleDbCommand : DbCommand, 
    ICloneable, IDbCommand, IDisposable
Visual C++
public ref class OleDbCommand sealed : public DbCommand, 
    ICloneable, IDbCommand, IDisposable
F#
[<Sealed>]
type OleDbCommand =  
    class
        inherit DbCommand
        interface ICloneable
        interface IDbCommand
        interface IDisposable
    end

The OleDbCommand type exposes the following members.

  NameDescription
Public methodOleDbCommand()()()Initializes a new instance of the OleDbCommand class.
Public methodOleDbCommand(String)Initializes a new instance of the OleDbCommand class with the text of the query.
Public methodOleDbCommand(String, OleDbConnection)Initializes a new instance of the OleDbCommand class with the text of the query and an OleDbConnection.
Public methodOleDbCommand(String, OleDbConnection, OleDbTransaction)Initializes a new instance of the OleDbCommand class with the text of the query, an OleDbConnection, and the Transaction.
Top
  NameDescription
Protected propertyCanRaiseEventsGets a value indicating whether the component can raise an event. (Inherited from Component.)
Public propertyCommandTextGets or sets the SQL statement or stored procedure to execute at the data source. (Overrides DbCommand..::.CommandText.)
Public propertyCommandTimeoutGets or sets the wait time before terminating an attempt to execute a command and generating an error. (Overrides DbCommand..::.CommandTimeout.)
Public propertyCommandTypeGets or sets a value that indicates how the CommandText property is interpreted. (Overrides DbCommand..::.CommandType.)
Public propertyConnectionGets or sets the OleDbConnection used by this instance of the OleDbCommand.
Public propertyContainerGets the IContainer that contains the Component. (Inherited from Component.)
Protected propertyDbConnectionGets or sets the DbConnection used by this DbCommand. (Inherited from DbCommand.)
Protected propertyDbParameterCollectionGets the collection of DbParameter objects. (Inherited from DbCommand.)
Protected propertyDbTransactionGets or sets the DbTransaction within which this DbCommand object executes. (Inherited from DbCommand.)
Protected propertyDesignModeGets a value that indicates whether the Component is currently in design mode. (Inherited from Component.)
Public propertyDesignTimeVisibleGets or sets a value that indicates whether the command object should be visible in a customized Windows Forms Designer control. (Overrides DbCommand..::.DesignTimeVisible.)
Protected propertyEventsGets the list of event handlers that are attached to this Component. (Inherited from Component.)
Public propertyParametersGets the OleDbParameterCollection.
Public propertySiteGets or sets the ISite of the Component. (Inherited from Component.)
Public propertyTransactionGets or sets the OleDbTransaction within which the OleDbCommand executes.
Public propertyUpdatedRowSourceGets or sets how command results are applied to the DataRow when used by the Update method of the OleDbDataAdapter. (Overrides DbCommand..::.UpdatedRowSource.)
Top
  NameDescription
Public methodCancelTries to cancel the execution of an OleDbCommand. (Overrides DbCommand..::.Cancel()()().)
Public methodCloneCreates a new OleDbCommand object that is a copy of the current instance.
Protected methodCreateDbParameterCreates a new instance of a DbParameter object. (Inherited from DbCommand.)
Public methodCreateObjRefCreates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.)
Public methodCreateParameterCreates a new instance of an OleDbParameter object.
Public methodDispose()()()Releases all resources used by the Component. (Inherited from Component.)
Protected methodDispose(Boolean)Releases the unmanaged resources used by the Component and optionally releases the managed resources. (Inherited from Component.)
Public methodEquals(Object)Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected methodExecuteDbDataReaderExecutes the command text against the connection. (Inherited from DbCommand.)
Public methodExecuteNonQueryExecutes an SQL statement against the Connection and returns the number of rows affected. (Overrides DbCommand..::.ExecuteNonQuery()()().)
Public methodExecuteReader()()()Sends the CommandText to the Connection and builds an OleDbDataReader.
Public methodExecuteReader(CommandBehavior)Sends the CommandText to the Connection, and builds an OleDbDataReader using one of the CommandBehavior values.
Public methodExecuteScalarExecutes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored. (Overrides DbCommand..::.ExecuteScalar()()().)
Protected methodFinalizeReleases unmanaged resources and performs other cleanup operations before the Component is reclaimed by garbage collection. (Inherited from Component.)
Public methodGetHashCodeServes as a hash function for a particular type. (Inherited from Object.)
Public methodGetLifetimeServiceRetrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Protected methodGetServiceReturns an object that represents a service provided by the Component or by its Container. (Inherited from Component.)
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodInitializeLifetimeServiceObtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Protected methodMemberwiseClone()()()Creates a shallow copy of the current Object. (Inherited from Object.)
Protected methodMemberwiseClone(Boolean)Creates a shallow copy of the current MarshalByRefObject object. (Inherited from MarshalByRefObject.)
Public methodPrepareCreates a prepared (or compiled) version of the command on the data source. (Overrides DbCommand..::.Prepare()()().)
Public methodResetCommandTimeoutResets the CommandTimeout property to the default value.
Public methodToStringReturns a String containing the name of the Component, if any. This method should not be overridden. (Inherited from Component.)
Top
  NameDescription
Public eventDisposedOccurs when the component is disposed by a call to the Dispose method. (Inherited from Component.)
Top
  NameDescription
Explicit interface implemetationPrivate methodICloneable..::.CloneFor a description of this member, see ICloneable..::.Clone.
Explicit interface implemetationPrivate propertyIDbCommand..::.ConnectionGets or sets the IDbConnection used by this instance of the IDbCommand. (Inherited from DbCommand.)
Explicit interface implemetationPrivate methodIDbCommand..::.CreateParameterCreates a new instance of an IDbDataParameter object. (Inherited from DbCommand.)
Explicit interface implemetationPrivate methodIDbCommand..::.ExecuteReader()()()For a description of this member, see IDbCommand..::.ExecuteReader.
Explicit interface implemetationPrivate methodIDbCommand..::.ExecuteReader(CommandBehavior)Executes the CommandText against the Connection, and builds an IDataReader using one of the CommandBehavior values.
Explicit interface implemetationPrivate propertyIDbCommand..::.ParametersGets the IDataParameterCollection. (Inherited from DbCommand.)
Explicit interface implemetationPrivate propertyIDbCommand..::.TransactionGets or sets the DbTransaction within which this DbCommand object executes. (Inherited from DbCommand.)
Top

When an instance of OleDbCommand is created, the read/write properties are set to their initial values. For a list of these values, see the OleDbCommand constructor.

OleDbCommand features the following methods executing commands at a data source:

Item

Description

ExecuteReader

Executes commands that return rows. ExecuteReader may not have the effect that you want if used to execute commands such as SQL SET statements.

ExecuteNonQuery

Executes commands such as SQL INSERT, DELETE, UPDATE, and SET statements.

ExecuteScalar

Retrieves a single value, for example, an aggregate value from a database.

You can reset the CommandText property and reuse the OleDbCommand object. However, you must close the OleDbDataReader before you can execute a new or previous command.

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. However, the user can reopen the connection and continue.

The following example uses the OleDbCommand, along OleDbDataAdapter and OleDbConnection, to select rows from an Access database. The filled DataSet is then returned. 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.

Visual Basic
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
C#
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();
    }
}

.NET Framework

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role not supported), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Biblioteca de clases de .NET Framework
OleDbCommand (Clase)

Representa una instrucción SQL o un procedimiento almacenado que se va a ejecutar en un origen de datos.

System..::.Object
  System..::.MarshalByRefObject
    System.ComponentModel..::.Component
      System.Data.Common..::.DbCommand
        System.Data.OleDb..::.OleDbCommand

Espacio de nombres:  System.Data.OleDb
Ensamblado:  System.Data (en System.Data.dll)
Visual Basic
Public NotInheritable Class OleDbCommand _
    Inherits DbCommand _
    Implements ICloneable, IDbCommand, IDisposable
C#
public sealed class OleDbCommand : DbCommand, 
    ICloneable, IDbCommand, IDisposable
Visual C++
public ref class OleDbCommand sealed : public DbCommand, 
    ICloneable, IDbCommand, IDisposable
F#
[<Sealed>]
type OleDbCommand =  
    class
        inherit DbCommand
        interface ICloneable
        interface IDbCommand
        interface IDisposable
    end

El tipo OleDbCommand expone los siguientes miembros.

  NombreDescripción
Método públicoOleDbCommand()()()Inicializa una nueva instancia de la clase OleDbCommand.
Método públicoOleDbCommand(String)Inicializa una nueva instancia de la clase OleDbCommand con el texto de la consulta.
Método públicoOleDbCommand(String, OleDbConnection)Inicializa una nueva instancia de la clase OleDbCommand con el texto de la consulta y OleDbConnection.
Método públicoOleDbCommand(String, OleDbConnection, OleDbTransaction)Inicializa una nueva instancia de la clase OleDbCommand con el texto de la consulta, OleDbConnection y Transaction.
Arriba
  NombreDescripción
Propiedad protegidaCanRaiseEventsObtiene un valor que indica si el componente puede generar un evento. (Se hereda de Component).
Propiedad públicaCommandTextObtiene o establece la instrucción SQL o el procedimiento almacenado que se va a ejecutar en el origen de datos. (Invalida a DbCommand..::.CommandText).
Propiedad públicaCommandTimeoutObtiene o establece el tiempo de espera hasta que se interrumpa el intento de ejecutar un comando y se genere un error. (Invalida a DbCommand..::.CommandTimeout).
Propiedad públicaCommandTypeObtiene o establece un valor que indica cómo se interpreta la propiedad CommandText. (Invalida a DbCommand..::.CommandType).
Propiedad públicaConnectionObtiene o establece la conexión OleDbConnection que utiliza esta instancia de OleDbCommand.
Propiedad públicaContainerObtiene IContainer que contiene Component. (Se hereda de Component).
Propiedad protegidaDbConnectionObtiene o establece el objeto DbConnection que utiliza este DbCommand. (Se hereda de DbCommand).
Propiedad protegidaDbParameterCollectionObtiene la colección de objetos DbParameter. (Se hereda de DbCommand).
Propiedad protegidaDbTransactionObtiene o establece la transacción DbTransaction en la que se ejecuta este objeto DbCommand. (Se hereda de DbCommand).
Propiedad protegidaDesignModeObtiene un valor que indica si Component está actualmente en modo de diseño. (Se hereda de Component).
Propiedad públicaDesignTimeVisibleObtiene o establece un valor que indica si el objeto de comando debe estar visible en un control personalizado del Diseñador de Windows Forms. (Invalida a DbCommand..::.DesignTimeVisible).
Propiedad protegidaEventsObtiene la lista de controladores de eventos asociados a Component. (Se hereda de Component).
Propiedad públicaParametersObtiene OleDbParameterCollection.
Propiedad públicaSiteObtiene o establece ISite de Component. (Se hereda de Component).
Propiedad públicaTransactionObtiene o establece la transacción OleDbTransaction en la que se ejecuta OleDbCommand.
Propiedad públicaUpdatedRowSourceObtiene o establece la manera en que se aplican los resultados del comando a DataRow cuando lo utiliza el método Update del OleDbDataAdapter. (Invalida a DbCommand..::.UpdatedRowSource).
Arriba
  NombreDescripción
Método públicoCancelIntenta cancelar la ejecución de OleDbCommand. (Invalida a DbCommand..::.Cancel()()()).
Método públicoCloneCrea un nuevo objeto OleDbCommand que es una copia de la instancia actual.
Método protegidoCreateDbParameterCrea una nueva instancia de un objeto DbParameter. (Se hereda de DbCommand).
Método públicoCreateObjRefCrea un objeto que contiene toda la información relevante necesaria para generar un proxy utilizado para comunicarse con un objeto remoto. (Se hereda de MarshalByRefObject).
Método públicoCreateParameterCrea una nueva instancia de un objeto OleDbParameter.
Método públicoDispose()()()Libera todos los recursos utilizados por el objeto Component. (Se hereda de Component).
Método protegidoDispose(Boolean)Libera los recursos no administrados usados por Component y, opcionalmente, los recursos administrados. (Se hereda de Component).
Método públicoEquals(Object)Determina si el objeto Object especificado es igual al objeto Object actual. (Se hereda de Object).
Método protegidoExecuteDbDataReaderEjecuta el texto de comando en la conexión. (Se hereda de DbCommand).
Método públicoExecuteNonQueryEjecuta una instrucción SQL en Connection y devuelve el número de filas afectadas. (Invalida a DbCommand..::.ExecuteNonQuery()()()).
Método públicoExecuteReader()()()Envía CommandText a Connection y genera un objeto OleDbDataReader.
Método públicoExecuteReader(CommandBehavior)Envía CommandText a Connection y crea un objeto OleDbDataReader con uno de los valores de CommandBehavior.
Método públicoExecuteScalarEjecuta la consulta y devuelve la primera columna de la primera fila del conjunto de resultados devuelto por la consulta. Las demás columnas o filas no se tienen en cuenta. (Invalida a DbCommand..::.ExecuteScalar()()()).
Método protegidoFinalizeLibera recursos no administrados y realiza otras operaciones de limpieza antes de que se reclame el objeto Component durante la recolección de elementos no utilizados. (Se hereda de Component).
Método públicoGetHashCodeActúa como función hash para un tipo concreto. (Se hereda de Object).
Método públicoGetLifetimeServiceRecupera el objeto de servicio de duración actual que controla la directiva de duración de esta instancia. (Se hereda de MarshalByRefObject).
Método protegidoGetServiceDevuelve un objeto que representa el servicio suministrado por Component o por Container. (Se hereda de Component).
Método públicoGetTypeObtiene el objeto Type de la instancia actual. (Se hereda de Object).
Método públicoInitializeLifetimeServiceObtiene un objeto de servicio de duración para controlar la directiva de duración de esta instancia. (Se hereda de MarshalByRefObject).
Método protegidoMemberwiseClone()()()Crea una copia superficial del objeto Object actual. (Se hereda de Object).
Método protegidoMemberwiseClone(Boolean)Crea una copia superficial del objeto MarshalByRefObject actual. (Se hereda de MarshalByRefObject).
Método públicoPrepareCrea una versión preparada (o compilada) del comando en el origen de datos. (Invalida a DbCommand..::.Prepare()()()).
Método públicoResetCommandTimeoutRestablece el valor predeterminado de la propiedad CommandTimeout.
Método públicoToStringDevuelve un objeto String que contiene el nombre del objeto Component, en caso de que exista. Este método no debe reemplazarse. (Se hereda de Component).
Arriba
  NombreDescripción
Evento públicoDisposedSe produce cuando el componente se elimina mediante una llamada al método Dispose. (Se hereda de Component).
Arriba
  NombreDescripción
Implementación explícita de interfacesMétodo privadoICloneable..::.ClonePara obtener una descripción de este miembro, vea ICloneable..::.Clone.
Implementación explícita de interfacesPropiedad privadaIDbCommand..::.ConnectionObtiene o establece la interfaz IDbConnection que utiliza esta instancia de IDbCommand. (Se hereda de DbCommand).
Implementación explícita de interfacesMétodo privadoIDbCommand..::.CreateParameterCrea una nueva instancia de un objeto IDbDataParameter. (Se hereda de DbCommand).
Implementación explícita de interfacesMétodo privadoIDbCommand..::.ExecuteReader()()()Para obtener una descripción de este miembro, vea IDbCommand..::.ExecuteReader.
Implementación explícita de interfacesMétodo privadoIDbCommand..::.ExecuteReader(CommandBehavior)Ejecuta CommandText en Connection y genera un IDataReader mediante uno de los valores de CommandBehavior.
Implementación explícita de interfacesPropiedad privadaIDbCommand..::.ParametersObtiene IDataParameterCollection. (Se hereda de DbCommand).
Implementación explícita de interfacesPropiedad privadaIDbCommand..::.TransactionObtiene o establece la transacción DbTransaction en la que se ejecuta este objeto DbCommand. (Se hereda de DbCommand).
Arriba

Cuando se crea una instancia de OleDbCommand, las propiedades de lectura y escritura se establecen en sus valores iniciales. Para obtener una lista de esos valores, vea el constructor OleDbCommand.

OleDbCommand tiene los siguientes métodos que ejecutan comandos en el origen de datos:

Elemento

Descripción

ExecuteReader

Ejecuta comandos que devuelven filas. ExecuteReader puede no tener el efecto deseado si se utiliza para ejecutar comandos como las instrucciones SQL SET.

ExecuteNonQuery

Ejecuta comandos como instrucciones SQL INSERT, DELETE, UPDATE y SET.

ExecuteScalar

Recupera un único valor de una base de datos; por ejemplo, un valor agregado.

Se puede restablecer el valor de la propiedad CommandText y volver a utilizar el objeto OleDbCommand. Sin embargo, es necesario cerrar OleDbDataReader para poder ejecutar un comando nuevo o previo.

Si se genera una OleDbException grave (por ejemplo, un nivel de gravedad de SQL Server de 20 o superior) por parte del método que ejecuta un OleDbCommand, OleDbConnection, se podría cerrar la conexión. Sin embargo, el usuario puede volver a abrir la conexión y continuar.

En el ejemplo siguiente se utiliza OleDbCommand, junto con OleDbDataAdapter y OleDbConnection, para seleccionar filas de una base de datos de Access. A continuación, se devuelve DataSet rellenado. En el ejemplo se pasa DataSet inicializado, 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 la base de datos de origen.

Visual Basic
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
C#
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();
    }
}

.NET Framework

Compatible con: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Compatible con: 4, 3.5 SP1

Windows 7, Windows Vista SP1 o posterior, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (no se admite Server Core), Windows Server 2008 R2 (se admite Server Core con SP1 o posterior), Windows Server 2003 SP2

.NET Framework no admite todas las versiones de todas las plataformas. Para obtener una lista de las versiones compatibles, vea Requisitos de sistema de .NET Framework.
Todos los miembros static (Shared en Visual Basic) públicos de este tipo son seguros para la ejecución de subprocesos. No se garantiza que los miembros de instancias sean seguros para la ejecución de subprocesos.
Contenido de la comunidad   ¿Qué es Community Content?
Agregar contenido nuevo RSS  Anotaciones
Processing
© 2012 Microsoft. Reservados todos los derechos. Términos de uso | Marcas Registradas | Privacidad
Page view tracker