3 out of 5 rated this helpful - Rate this topic

SqlCommand Class

Represents a Transact-SQL statement or stored procedure to execute against a SQL Server database. This class cannot be inherited.

System.Object
  System.MarshalByRefObject
    System.ComponentModel.Component
      System.Data.Common.DbCommand
        System.Data.SqlClient.SqlCommand

Namespace:  System.Data.SqlClient
Assembly:  System.Data (in System.Data.dll)
public sealed class SqlCommand : DbCommand, 
	ICloneable

The SqlCommand type exposes the following members.

  Name Description
Public method SqlCommand() Initializes a new instance of the SqlCommand class.
Public method SqlCommand(String) Initializes a new instance of the SqlCommand class with the text of the query.
Public method SqlCommand(String, SqlConnection) Initializes a new instance of the SqlCommand class with the text of the query and a SqlConnection.
Public method SqlCommand(String, SqlConnection, SqlTransaction) Initializes a new instance of the SqlCommand class with the text of the query, a SqlConnection, and the SqlTransaction.
Top
  Name Description
Protected property CanRaiseEvents Gets a value indicating whether the component can raise an event. (Inherited from Component.)
Public property CommandText Gets or sets the Transact-SQL statement, table name or stored procedure to execute at the data source. (Overrides DbCommand.CommandText.)
Public property CommandTimeout Gets or sets the wait time before terminating the attempt to execute a command and generating an error. (Overrides DbCommand.CommandTimeout.)
Public property CommandType Gets or sets a value indicating how the CommandText property is to be interpreted. (Overrides DbCommand.CommandType.)
Public property Connection Gets or sets the SqlConnection used by this instance of the SqlCommand.
Public property Container Gets the IContainer that contains the Component. (Inherited from Component.)
Protected property DbConnection Gets or sets the DbConnection used by this DbCommand. (Inherited from DbCommand.)
Protected property DbParameterCollection Gets the collection of DbParameter objects. (Inherited from DbCommand.)
Protected property DbTransaction Gets or sets the DbTransaction within which this DbCommand object executes. (Inherited from DbCommand.)
Protected property DesignMode Gets a value that indicates whether the Component is currently in design mode. (Inherited from Component.)
Public property DesignTimeVisible Gets or sets a value indicating whether the command object should be visible in a Windows Form Designer control. (Overrides DbCommand.DesignTimeVisible.)
Protected property Events Gets the list of event handlers that are attached to this Component. (Inherited from Component.)
Public property Notification Gets or sets a value that specifies the SqlNotificationRequest object bound to this command.
Public property NotificationAutoEnlist Gets or sets a value indicating whether the application should automatically receive query notifications from a common SqlDependency object.
Public property Parameters Gets the SqlParameterCollection.
Public property Site Gets or sets the ISite of the Component. (Inherited from Component.)
Public property Transaction Gets or sets the SqlTransaction within which the SqlCommand executes.
Public property UpdatedRowSource Gets or sets how command results are applied to the DataRow when used by the Update method of the DbDataAdapter. (Overrides DbCommand.UpdatedRowSource.)
Top
  Name Description
Public method BeginExecuteNonQuery() Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this SqlCommand.
Public method BeginExecuteNonQuery(AsyncCallback, Object) Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this SqlCommand, given a callback procedure and state information.
Public method BeginExecuteReader() Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this SqlCommand, and retrieves one or more result sets from the server.
Public method BeginExecuteReader(CommandBehavior) Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this SqlCommand using one of the CommandBehavior values.
Public method BeginExecuteReader(AsyncCallback, Object) Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this SqlCommand and retrieves one or more result sets from the server, given a callback procedure and state information.
Public method BeginExecuteReader(AsyncCallback, Object, CommandBehavior) Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this SqlCommand, using one of the CommandBehavior values, and retrieving one or more result sets from the server, given a callback procedure and state information.
Public method BeginExecuteXmlReader() Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this SqlCommand and returns results as an XmlReader object.
Public method BeginExecuteXmlReader(AsyncCallback, Object) Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this SqlCommand and returns results as an XmlReader object, using a callback procedure.
Public method Cancel Tries to cancel the execution of a SqlCommand. (Overrides DbCommand.Cancel().)
Public method Clone Creates a new SqlCommand object that is a copy of the current instance.
Protected method CreateDbParameter Creates a new instance of a DbParameter object. (Inherited from DbCommand.)
Public method CreateObjRef Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.)
Public method CreateParameter Creates a new instance of a SqlParameter object.
Public method Dispose() Releases all resources used by the Component. (Inherited from Component.)
Protected method Dispose(Boolean) Releases the unmanaged resources used by the Component and optionally releases the managed resources. (Inherited from Component.)
Public method EndExecuteNonQuery Finishes asynchronous execution of a Transact-SQL statement.
Public method EndExecuteReader Finishes asynchronous execution of a Transact-SQL statement, returning the requested SqlDataReader.
Public method EndExecuteXmlReader Finishes asynchronous execution of a Transact-SQL statement, returning the requested data as XML.
Public method Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected method ExecuteDbDataReader Executes the command text against the connection. (Inherited from DbCommand.)
Public method ExecuteNonQuery Executes a Transact-SQL statement against the connection and returns the number of rows affected. (Overrides DbCommand.ExecuteNonQuery().)
Public method ExecuteReader() Sends the CommandText to the Connection and builds a SqlDataReader.
Public method ExecuteReader(CommandBehavior) Sends the CommandText to the Connection, and builds a SqlDataReader using one of the CommandBehavior values.
Public method ExecuteScalar Executes 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().)
Public method ExecuteXmlReader Sends the CommandText to the Connection and builds an XmlReader object.
Protected method Finalize Releases unmanaged resources and performs other cleanup operations before the Component is reclaimed by garbage collection. (Inherited from Component.)
Public method GetHashCode Serves as a hash function for a particular type. (Inherited from Object.)
Public method GetLifetimeService Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Protected method GetService Returns an object that represents a service provided by the Component or by its Container. (Inherited from Component.)
Public method GetType Gets the Type of the current instance. (Inherited from Object.)
Public method InitializeLifetimeService Obtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Protected method MemberwiseClone() Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method MemberwiseClone(Boolean) Creates a shallow copy of the current MarshalByRefObject object. (Inherited from MarshalByRefObject.)
Public method Prepare Creates a prepared version of the command on an instance of SQL Server. (Overrides DbCommand.Prepare().)
Public method ResetCommandTimeout Resets the CommandTimeout property to its default value.
Public method ToString Returns a String containing the name of the Component, if any. This method should not be overridden. (Inherited from Component.)
Top
  Name Description
Public event Disposed Occurs when the component is disposed by a call to the Dispose method. (Inherited from Component.)
Public event StatementCompleted Occurs when the execution of a Transact-SQL statement completes.
Top
  Name Description
Explicit interface implemetation Private method ICloneable.Clone Creates a new SqlCommand object that is a copy of the current instance.
Explicit interface implemetation Private property IDbCommand.Connection Gets or sets the IDbConnection used by this instance of the IDbCommand. (Inherited from DbCommand.)
Explicit interface implemetation Private method IDbCommand.CreateParameter Creates a new instance of an IDbDataParameter object. (Inherited from DbCommand.)
Explicit interface implemetation Private method IDbCommand.ExecuteReader() Executes the CommandText against the Connection and builds an IDataReader. (Inherited from DbCommand.)
Explicit interface implemetation Private method IDbCommand.ExecuteReader(CommandBehavior) Executes the CommandText against the Connection, and builds an IDataReader using one of the CommandBehavior values. (Inherited from DbCommand.)
Explicit interface implemetation Private property IDbCommand.Parameters Gets the IDataParameterCollection. (Inherited from DbCommand.)
Explicit interface implemetation Private property IDbCommand.Transaction Gets or sets the DbTransaction within which this DbCommand object executes. (Inherited from DbCommand.)
Top

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

SqlCommand features the following methods for executing commands at a SQL Server database:

Item

Description

BeginExecuteNonQuery

Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this SqlCommand, generally executing commands such as INSERT, DELETE, UPDATE, and SET statements. Each call to BeginExecuteNonQuery must be paired with a call to EndExecuteNonQuery which finishes the operation, typically on a separate thread.

BeginExecuteReader

Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this SqlCommand and retrieves one or more results sets from the server. Each call to BeginExecuteReader must be paired with a call to EndExecuteReader which finishes the operation, typically on a separate thread.

BeginExecuteXmlReader

Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this SqlCommand. Each call to BeginExecuteXmlReader must be paired with a call to EndExecuteXmlReader, which finishes the operation, typically on a separate thread, and returns an XmlReader object.

ExecuteReader

Executes commands that return rows. For increased performance, ExecuteReader invokes commands using the Transact-SQL sp_executesql system stored procedure. Therefore, ExecuteReader might not have the effect that you want if used to execute commands such as Transact-SQL SET statements.

ExecuteNonQuery

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

ExecuteScalar

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

ExecuteXmlReader

Sends the CommandText to the Connection and builds an XmlReader object.

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

If a SqlException is generated by the method executing a SqlCommand, the SqlConnection remains open when the severity level is 19 or less. When the severity level is 20 or greater, the server ordinarily closes the SqlConnection. However, the user can reopen the connection and continue.

Note Note

Nameless, also called ordinal, parameters are not supported by the .NET Framework Data Provider for SQL Server.

The following example creates a SqlConnection, a SqlCommand, and a SqlDataReader. The example reads through the data, writing it to the console. Finally, the example closes the SqlDataReader and then the SqlConnection as it exits the Using code blocks.


private static void ReadOrderData(string connectionString)
{
    string queryString = 
        "SELECT OrderID, CustomerID FROM dbo.Orders;";
    using (SqlConnection connection = new SqlConnection(
               connectionString))
    {
        SqlCommand command = new SqlCommand(
            queryString, connection);
        connection.Open();
        SqlDataReader reader = command.ExecuteReader();
        try
        {
            while (reader.Read())
            {
                Console.WriteLine(String.Format("{0}, {1}",
                    reader[0], reader[1]));
            }
        }
        finally
        {
            // 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 not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), 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.
Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
Dispose
Shouldn't the SqlCommand be disposed?