.NET Framework Class Library OleDbCommand Class Represents an SQL statement or stored procedure to execute against a data source.

Inheritance Hierarchy
Namespace:
System.Data.OleDb
Assembly:
System.Data (in System.Data.dll)

Syntax
Public NotInheritable Class OleDbCommand _
Inherits DbCommand _
Implements ICloneable, IDbCommand, IDisposable
public sealed class OleDbCommand : DbCommand,
ICloneable, IDbCommand, IDisposable
public ref class OleDbCommand sealed : public DbCommand,
ICloneable, IDbCommand, IDisposable
[<Sealed>]
type OleDbCommand =
class
inherit DbCommand
interface ICloneable
interface IDbCommand
interface IDisposable
end
The OleDbCommand type exposes the following members.

Constructors

Properties

Methods

Events

Explicit Interface Implementations

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

Examples
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.
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
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();
}
}

Version Information
.NET FrameworkSupported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0 .NET Framework Client ProfileSupported in: 4, 3.5 SP1

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

Thread Safety
Any public static ( Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also
|
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.

Jerarquía de herencia
Espacio de nombres:
System.Data.OleDb
Ensamblado:
System.Data (en System.Data.dll)

Sintaxis
Public NotInheritable Class OleDbCommand _
Inherits DbCommand _
Implements ICloneable, IDbCommand, IDisposable
public sealed class OleDbCommand : DbCommand,
ICloneable, IDbCommand, IDisposable
public ref class OleDbCommand sealed : public DbCommand,
ICloneable, IDbCommand, IDisposable
[<Sealed>]
type OleDbCommand =
class
inherit DbCommand
interface ICloneable
interface IDbCommand
interface IDisposable
end
El tipo OleDbCommand expone los siguientes miembros.

Constructores

Propiedades

Métodos

Eventos

Implementaciones explícitas de interfaces

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

Ejemplos
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.
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
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();
}
}

Información de versión
.NET FrameworkCompatible con: 4, 3.5, 3.0, 2.0, 1.1, 1.0 .NET Framework Client ProfileCompatible con: 4, 3.5 SP1

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

Seguridad para subprocesos
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.

Vea también
|