Friday, March 25, 2011

Sql Command


cmd.EndExecuteNonQuery;
cmd.EndExecuteReader;
cmd.EndExecuteXmlReader;

cmd.ExecuteNonQuery();
cmd.ExecuteReader();
cmd.ExecuteScalar();
cmd.BeginExecuteNonQuery();
cmd.BeginExecuteReader();
cmd.BeginExecuteXmlReader();

cmd.GetHashCode();
cmd.Prepare();
cmd.StatementCompleted();

EndExecuteNonQuery method


Finishes asynchronous execution of a SQL statement or stored procedure.
Syntax

Visual Basic

Public Function EndExecuteNonQuery( _
   ByVal asyncResult As IAsyncResult _
) As Integer
C#

public int EndExecuteNonQuery(
   IAsyncResult asyncResult
);

Parameters
  • asyncResult   The IAsyncResult returned by the call to SACommand.BeginExecuteNonQuery.
Return value
The number of rows affected (the same behavior as SACommand.ExecuteNonQuery).
Remarks
You must call EndExecuteNonQuery once for every call to BeginExecuteNonQuery. The call must be after BeginExecuteNonQuery has returned.ADO.NET is not thread safe; it is your responsibility to ensure that BeginExecuteNonQuery has returned. The IAsyncResult passed to EndExecuteNonQuery must be the same as the one returned from the BeginExecuteNonQuery call that is being completed. It is an error to call EndExecuteNonQuery to end a call to BeginExecuteReader, and vice versa.
If an error occurs while executing the command, the exception is thrown when EndExecuteNonQuery is called.
There are four ways to wait for execution to complete:
(1) Call EndExecuteNonQuery.
Calling EndExecuteNonQuery blocks until the command completes. For example:
SAConnection conn = new SAConnection("DSN=SQL Anywhere 11 Demo");
conn.Open();
SACommand cmd = new SACommand( 
  "UPDATE Departments"
    + " SET DepartmentName = 'Engineering'"
    + " WHERE DepartmentID=100",
  conn );
IAsyncResult res = cmd.BeginExecuteNonQuery();
// perform other work
// this will block until the command completes
int rowCount reader = cmd.EndExecuteNonQuery( res );
(2) Poll the IsCompleted property of the IAsyncResult.
You can poll the IsCompleted property of the IAsyncResult. For example:
SAConnection conn = new SAConnection("DSN=SQL Anywhere 11 Demo");
conn.Open();
SACommand cmd = new SACommand( 
  "UPDATE Departments"
    + " SET DepartmentName = 'Engineering'"
    + " WHERE DepartmentID=100",
    conn
  );
IAsyncResult res = cmd.BeginExecuteNonQuery();
while( !res.IsCompleted ) {
// do other work
}
// this will not block because the command is finished
int rowCount = cmd.EndExecuteNonQuery( res );
(3) Use the IAsyncResult.AsyncWaitHandle property to get a synchronization object.
You can use the IAsyncResult.AsyncWaitHandle property to get a synchronization object, and wait on that. For example:
SAConnection conn = new SAConnection("DSN=SQL Anywhere 11 Demo");
conn.Open();
SACommand cmd = new SACommand( 
  "UPDATE Departments"
    + " SET DepartmentName = 'Engineering'"
    + " WHERE DepartmentID=100",
    conn
  );
IAsyncResult res = cmd.BeginExecuteNonQuery();
// perform other work
WaitHandle wh = res.AsyncWaitHandle;
wh.WaitOne();
// this will not block because the command is finished
int rowCount = cmd.EndExecuteNonQuery( res );
(4) Specify a callback function when calling BeginExecuteNonQuery.
You can specify a callback function when calling BeginExecuteNonQuery. For example:
private void callbackFunction( IAsyncResult ar )
{
   SACommand cmd = (SACommand) ar.AsyncState;
   // this won't block since the command has completed
            int rowCount = cmd.EndExecuteNonQuery();
}
// elsewhere in the code
private void DoStuff() 
{
      SAConnection conn = new SAConnection("DSN=SQL Anywhere 11 Demo");
      conn.Open();
            SACommand cmd = new SACommand(
        "UPDATE Departments"
    + " SET DepartmentName = 'Engineering'"
    + " WHERE DepartmentID=100",
    conn
  );
   IAsyncResult res = cmd.BeginExecuteNonQuery( callbackFunction, cmd );
   // perform other work.  The callback function will be 
   // called when the command completes
}
The callback function executes in a separate thread, so the usual caveats related to updating the user interface in a threaded program apply.

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

EndExecuteNonQuery method


Finishes asynchronous execution of a SQL statement.
 Visual Basic syntax
Public Function EndExecuteNonQuery(
    ByVal asyncResult As IAsyncResult
) As Integer
 C# syntax
public int EndExecuteNonQuery(IAsyncResult asyncResult)
 Parameters
  • asyncResult   The System.IAsyncResult returned by the call to BeginExecuteNonQuery.
 Returns
The number of rows affected (the same behavior as ExecuteNonQuery).
 Exceptions
  • ArgumentException   The asyncResult parameter is null (Nothing in Microsoft Visual Basic).
  • InvalidOperationException   The EndExecuteNonQuery(IAsyncResult) was called more than once for a single command execution, or the method was mismatched against its execution method.
 Remarks
You must call EndExecuteNonQuery once for every call to BeginExecuteNonQuery. The call must be after BeginExecuteNonQuery has returned. ADO.NET is not thread safe; it is your responsibility to ensure that BeginExecuteNonQuery has returned. The System.IAsyncResult passed to EndExecuteNonQuery must be the same as the one returned from the BeginExecuteNonQuery call that is being completed. It is an error to call EndExecuteNonQuery to end a call to BeginExecuteReader, and vice versa.
If an error occurs while executing the command, the exception is thrown when EndExecuteNonQuery is called.
There are four ways to wait for execution to complete:
Call EndExecuteNonQuery Calling EndExecuteNonQuery blocks until the command completes. For example:



' Visual Basic
Dim cmd As ULCommand = new ULCommand( _
    "UPDATE Departments" _
    + " SET DepartmentName = 'Engineering'" _
    + " WHERE DepartmentID=100", _
    conn _
)

Dim res As IAsyncResult res = _
    cmd.BeginExecuteNonQuery()

' Perform other work.

' This blocks until the command completes.
Dim rowCount As Integer = _
    cmd.EndExecuteNonQuery( res )
The following code is the C# language equivalent:



// C#
ULCommand cmd = new ULCommand(
    "UPDATE Departments"
    + " SET DepartmentName = 'Engineering'"
    + " WHERE DepartmentID=100",
    conn
);

IAsyncResult res = cmd.BeginExecuteNonQuery();

// Perform other work.

// This blocks until the command completes.
int rowCount = cmd.EndExecuteNonQuery( res );
Poll the IsCompleted property of the IAsyncResult You can poll the IsCompleted property of the IAsyncResult. For example:

' Visual Basic
Dim cmd As ULCommand = new ULCommand( _
    "UPDATE Departments" _
    + " SET DepartmentName = 'Engineering'" _
    + " WHERE DepartmentID=100", _
    conn _
)

Dim res As IAsyncResult res = _
    cmd.BeginExecuteNonQuery()
While( !res.IsCompleted )
    ' Perform other work.
End While

' This blocks until the command completes.
Dim rowCount As Integer = _
    cmd.EndExecuteNonQuery( res )
The following code is the C# language equivalent:



// C#
ULCommand cmd = new ULCommand(
    "UPDATE Departments"
    + " SET DepartmentName = 'Engineering'"
    + " WHERE DepartmentID=100",
    conn
);

IAsyncResult res = cmd.BeginExecuteNonQuery();
while( !res.IsCompleted ) {
    // Perform other work.
}

// This blocks until the command completes.
int rowCount = cmd.EndExecuteNonQuery( res );
Use the IAsyncResult.AsyncWaitHandle property to get a synchronization object You can use the IAsyncResult.AsyncWaitHandle property to get a synchronization object, and wait on that. For example:



' Visual Basic
Dim cmd As ULCommand = new ULCommand( _
    "UPDATE Departments" _
    + " SET DepartmentName = 'Engineering'" _
    + " WHERE DepartmentID=100", _
    conn _
)
Dim res As IAsyncResult res = _
    cmd.BeginExecuteNonQuery()

' Perform other work.

Dim wh As WaitHandle = res.AsyncWaitHandle
wh.WaitOne()
' This does not block because the command is finished.
Dim rowCount As Integer = _
  cmd.EndExecuteNonQuery( res )
The following code is the C# language equivalent:



// C#
ULCommand cmd = new ULCommand(
    "UPDATE Departments"
    + " SET DepartmentName = 'Engineering'"
    + " WHERE DepartmentID=100",
    conn
  );
IAsyncResult res = cmd.BeginExecuteNonQuery();
// perform other work
WaitHandle wh = res.AsyncWaitHandle;
wh.WaitOne();
// This does not block because the command is finished.
int rowCount = cmd.EndExecuteNonQuery( res );
Specify a callback function when calling BeginExecuteNonQuery You can specify a callback function when calling BeginExecuteNonQuery. For example:



' Visual Basic
Private Sub callbackFunction(ByVal ar As IAsyncResult)
    Dim cmd As ULCommand = _
        CType(ar.AsyncState, ULCommand)
    ' This won't block since the command has completed.
    Dim rowCount As Integer = _
        cmd.EndExecuteNonQuery( res )
End Sub

' Elsewhere in the code
Private Sub DoStuff()
    Dim cmd As ULCommand = new ULCommand( _
        "UPDATE Departments" _
        + " SET DepartmentName = 'Engineering'" _
        + " WHERE DepartmentID=100", _
        conn _
    )
    Dim res As IAsyncResult = _
        cmd.BeginExecuteNonQuery( _
        callbackFunction, cmd _
    )
    ' Perform other work.  The callback function
    ' is called when the command completes.
End Sub
The following code is the C# language equivalent:



// C#
private void callbackFunction( IAsyncResult ar )
{
    ULCommand cmd = (ULCommand) ar.AsyncState;
    // This won't block since the command has completed.
    int rowCount = cmd.EndExecuteNonQuery();
}

// Elsewhere in the code
private void DoStuff()
{
    ULCommand cmd = new ULCommand(
        "UPDATE Departments"
        + " SET DepartmentName = 'Engineering'"
        + " WHERE DepartmentID=100",
        conn
    );
    IAsyncResult res = cmd.BeginExecuteNonQuery(
        callbackFunction, cmd
    );
    // Perform other work.  The callback function
    // is called when the command completes.
}
The callback function executes in a separate thread, so the usual caveats related to updating the user interface in a threaded program apply.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

EndExecuteReader method


Finishes asynchronous execution of a SQL statement or stored procedure, returning the requested SADataReader.
 Visual Basic syntax
Public Function EndExecuteReader(
    ByVal asyncResult As IAsyncResult
) As SADataReader
 C# syntax
public SADataReader EndExecuteReader(IAsyncResult asyncResult)
 Parameters
  • asyncResult   The IAsyncResult returned by the call to SACommand.BeginExecuteReader.
 Returns
An SADataReader object that can be used to retrieve the requested rows (the same behavior as SACommand.ExecuteReader).
 Exceptions
  • ArgumentException   The asyncResult parameter is null (Nothing in Microsoft Visual Basic)
  • InvalidOperationException   The SACommand.EndExecuteReader(IAsyncResult) was called more than once for a single command execution, or the method was mismatched against its execution method.
 Remarks
You must call EndExecuteReader once for every call to BeginExecuteReader. The call must be after BeginExecuteReader has returned.ADO.NET is not thread safe; it is your responsibility to ensure that BeginExecuteReader has returned. The IAsyncResult passed to EndExecuteReader must be the same as the one returned from the BeginExecuteReader call that is being completed. It is an error to call EndExecuteReader to end a call to BeginExecuteNonQuery, and vice versa.
If an error occurs while executing the command, the exception is thrown when EndExecuteReader is called.
There are four ways to wait for execution to complete:
(1) Call EndExecuteReader.
Calling EndExecuteReader blocks until the command completes. For example:

SAConnection conn = new SAConnection("DSN=SQL Anywhere 12 Demo");
conn.Open();
SACommand cmd = new SACommand( "SELECT * FROM Departments", conn );
IAsyncResult res = cmd.BeginExecuteReader();
// perform other work
// this blocks until the command completes
SADataReader reader = cmd.EndExecuteReader( res );
(2) Poll the IsCompleted property of the IAsyncResult.
You can poll the IsCompleted property of the IAsyncResult. For example:

SAConnection conn = new SAConnection("DSN=SQL Anywhere 12 Demo");
conn.Open();
SACommand cmd = new SACommand( "SELECT * FROM Departments", conn );
IAsyncResult res = cmd.BeginExecuteReader();
while( !res.IsCompleted ) {
    // do other work
}
// this does not block because the command is finished
SADataReader reader = cmd.EndExecuteReader( res );
(3) Use the IAsyncResult.AsyncWaitHandle property to get a synchronization object.
You can use the IAsyncResult.AsyncWaitHandle property to get a synchronization object, and wait on that. For example:

SAConnection conn = new SAConnection("DSN=SQL Anywhere 12 Demo");
conn.Open();
SACommand cmd = new SACommand( "SELECT * FROM Departments", conn );
IAsyncResult res = cmd.BeginExecuteReader();
// perform other work
WaitHandle wh = res.AsyncWaitHandle;
wh.WaitOne();
// this does not block because the command is finished
SADataReader reader = cmd.EndExecuteReader( res );
(4) Specify a callback function when calling BeginExecuteReader
You can specify a callback function when calling BeginExecuteReader. For example:



private void callbackFunction( IAsyncResult ar ) {
    SACommand cmd = (SACommand) ar.AsyncState;
    // this does not block since the command has completed
    SADataReader reader = cmd.EndExecuteReader();
}

// elsewhere in the code
private void DoStuff() {
    SAConnection conn = new SAConnection("DSN=SQL Anywhere 12 Demo");
    conn.Open();
    SACommand cmd = new SACommand( "SELECT * FROM Departments", conn );
    IAsyncResult res = cmd.BeginExecuteReader( callbackFunction, cmd );
    // perform other work.  The callback function will be
    // called when the command completes
}
The callback function executes in a separate thread, so the usual caveats related to updating the user interface in a threaded program apply.

BeginExecuteReader method


Initiates the asynchronous execution of a SQL statement or stored procedure that is described by this SACommand, and retrieves one or more result sets from the database server.
 
NameDescription
Initiates the asynchronous execution of a SQL statement or stored procedure that is described by this SACommand, and retrieves one or more result sets from the database server.
Initiates the asynchronous execution of a SQL statement that is described by the SACommand object, and retrieves the result set, given a callback procedure and state information.
Initiates the asynchronous execution of a SQL statement or stored procedure that is described by this SACommand, and retrieves one or more result sets from the server.
Initiates the asynchronous execution of a SQL statement or stored procedure that is described by this SACommand, and retrieves one or more result sets from the server.


>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>



Use the ExecuteScalar method to retrieve a single value (for example, an aggregate value) from a database. This requires less code than using the ExecuteReader method, and then performing the operations that you need to generate the single value using the data returned by a SqlDataReader.
A typical ExecuteScalar query can be formatted as in the following C# example:




cmd.CommandText = "SELECT COUNT(*) FROM dbo.region";
 Int32 count = (Int32) cmd.ExecuteScalar();


static public int AddProductCategory(string newName, string connString)
{
    Int32 newProdID = 0;
    string sql =
        "INSERT INTO Production.ProductCategory (Name) VALUES (@Name); "
        + "SELECT CAST(scope_identity() AS int)";
    using (SqlConnection conn = new SqlConnection(connString))
    {
        SqlCommand cmd = new SqlCommand(sql, conn);
        cmd.Parameters.Add("@Name", SqlDbType.VarChar);
        cmd.Parameters["@name"].Value = newName;
        try
        {
            conn.Open();
            newProdID = (Int32)cmd.ExecuteScalar();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
    return (int)newProdID;
}
using System;
using System.Data;
using System.Data.SqlClient;

   class CommandExampleScalar
   {
      static void Main() 
      {
         SqlConnection thisConnection = new SqlConnection("server=(local)\\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI");

         SqlCommand thisCommand = new SqlCommand("SELECT COUNT(*) FROM Employee", thisConnection);

         try {
            thisConnection.Open();

            Console.WriteLine("Number of Employees is: {0}",
               thisCommand.ExecuteScalar());
         }
         catch (SqlException ex
         {
            Console.WriteLine(ex.ToString());
         }
         finally 
         {
            thisConnection.Close();
            Console.WriteLine("Connection Closed.");
         }
      }
   }

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>.


SqlCommand Class

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


Namespace:  System.Data.SqlClient
Assembly:  System.Data (in System.Data.dll)


public sealed class SqlCommand : DbCommand, 
 ICloneable
The SqlCommand type exposes the following members.

NameDescription
Public methodSqlCommand()Initializes a new instance of the SqlCommand class.
Public methodSqlCommand(String)Initializes a new instance of the SqlCommand class with the text of the query.
Public methodSqlCommand(String, SqlConnection)Initializes a new instance of the SqlCommand class with the text of the query and a SqlConnection.
Public methodSqlCommand(String, SqlConnection, SqlTransaction)Initializes a new instance of the SqlCommand class with the text of the query, a SqlConnection, and the SqlTransaction.


NameDescription
Protected propertyCanRaiseEventsGets a value indicating whether the component can raise an event. (Inherited from Component.)
Public propertyCommandTextGets or sets the Transact-SQL statement, table name or stored procedure to execute at the data source. (OverridesDbCommand.CommandText.)
Public propertyCommandTimeoutGets or sets the wait time before terminating the attempt to execute a command and generating an error. (OverridesDbCommand.CommandTimeout.)
Public propertyCommandTypeGets or sets a value indicating how the CommandText property is to be interpreted. (Overrides DbCommand.CommandType.)
Public propertyConnectionGets or sets the SqlConnection used by this instance of theSqlCommand.
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 fromDbCommand.)
Protected propertyDbTransactionGets or sets the DbTransaction within which this DbCommandobject 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 indicating whether the command object should be visible in a Windows Form Designer control. (OverridesDbCommand.DesignTimeVisible.)
Protected propertyEventsGets the list of event handlers that are attached to thisComponent. (Inherited from Component.)
Public propertyNotificationGets or sets a value that specifies the SqlNotificationRequestobject bound to this command.
Public propertyNotificationAutoEnlistGets or sets a value indicating whether the application should automatically receive query notifications from a commonSqlDependency object.
Public propertyParametersGets the SqlParameterCollection.
Public propertySiteGets or sets the ISite of the Component. (Inherited fromComponent.)
Public propertyTransactionGets or sets the SqlTransaction within which the SqlCommandexecutes.
Public propertyUpdatedRowSourceGets or sets how command results are applied to the DataRowwhen used by the Update method of the DbDataAdapter.(Overrides DbCommand.UpdatedRowSource.)


NameDescription
Public methodBeginExecuteNonQuery()Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this SqlCommand.
Public methodBeginExecuteNonQuery(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 methodBeginExecuteReader()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 methodBeginExecuteReader(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 methodBeginExecuteReader(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 methodBeginExecuteReader(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 methodBeginExecuteXmlReader()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 methodBeginExecuteXmlReader(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 methodCancelTries to cancel the execution of aSqlCommand. (Overrides DbCommand.Cancel().)
Public methodCloneCreates a new SqlCommand object that is a copy of the current instance.
Protected methodCreateDbParameterCreates a new instance of a DbParameterobject. (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 a SqlParameterobject.
Public methodDispose()Releases all resources used by the Component.(Inherited from Component.)
Protected methodDispose(Boolean)Releases the unmanaged resources used by theComponent and optionally releases the managed resources. (Inherited fromComponent.)
Public methodEndExecuteNonQueryFinishes asynchronous execution of a Transact-SQL statement.
Public methodEndExecuteReaderFinishes asynchronous execution of a Transact-SQL statement, returning the requested SqlDataReader.
Public methodEndExecuteXmlReaderFinishes asynchronous execution of a Transact-SQL statement, returning the requested data as XML.
Public methodEquals(Object)Determines whether the specified Object is equal to the current Object. (Inherited fromObject.)
Protected methodExecuteDbDataReaderExecutes the command text against the connection. (Inherited from DbCommand.)
Public methodExecuteNonQueryExecutes a Transact-SQL statement against the connection and returns the number of rows affected. (OverridesDbCommand.ExecuteNonQuery().)
Public methodExecuteReader()Sends the CommandText to the Connectionand builds a SqlDataReader.
Public methodExecuteReader(CommandBehavior)Sends the CommandText to the Connection, and builds a SqlDataReader using one of theCommandBehavior 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. (OverridesDbCommand.ExecuteScalar().)
Public methodExecuteXmlReaderSends the CommandText to the Connectionand builds an XmlReader object.
Protected methodFinalizeReleases unmanaged resources and performs other cleanup operations before the Componentis 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 fromMarshalByRefObject.)
Protected methodMemberwiseClone()Creates a shallow copy of the current Object.(Inherited from Object.)
Protected methodMemberwiseClone(Boolean)Creates a shallow copy of the currentMarshalByRefObject object. (Inherited fromMarshalByRefObject.)
Public methodPrepareCreates a prepared version of the command on an instance of SQL Server. (OverridesDbCommand.Prepare().)
Public methodResetCommandTimeoutResets the CommandTimeout property to its default value.
Public methodToStringReturns a String containing the name of theComponent, if any. This method should not be overridden. (Inherited from Component.)


NameDescription
Public eventDisposedOccurs when the component is disposed by a call to the Disposemethod. (Inherited from Component.)
Public eventStatementCompletedOccurs when the execution of a Transact-SQL statement completes.


NameDescription
Explicit interface implemetation Private methodICloneable.CloneCreates a new SqlCommand object that is a copy of the current instance.
Explicit interface implemetation Private propertyIDbCommand.ConnectionGets or sets the IDbConnection used by this instance of the IDbCommand.(Inherited from DbCommand.)
Explicit interface implemetation Private methodIDbCommand.CreateParameterCreates a new instance of anIDbDataParameter object. (Inherited from DbCommand.)
Explicit interface implemetation Private methodIDbCommand.ExecuteReader()Executes the CommandText against the Connection and builds anIDataReader. (Inherited fromDbCommand.)
Explicit interface implemetation Private methodIDbCommand.ExecuteReader(CommandBehavior)Executes the CommandText against the Connection, and builds anIDataReader using one of theCommandBehavior values. (Inherited from DbCommand.)
Explicit interface implemetation Private propertyIDbCommand.ParametersGets the IDataParameterCollection.(Inherited from DbCommand.)
Explicit interface implemetation Private propertyIDbCommand.TransactionGets or sets the DbTransaction within which this DbCommand object executes. (Inherited fromDbCommand.)

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:
ItemDescription
BeginExecuteNonQueryInitiates 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 toEndExecuteNonQuery which finishes the operation, typically on a separate thread.
BeginExecuteReaderInitiates 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.
BeginExecuteXmlReaderInitiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this SqlCommand. Each call toBeginExecuteXmlReader must be paired with a call to EndExecuteXmlReader, which finishes the operation, typically on a separate thread, and returns anXmlReader object.
ExecuteReaderExecutes commands that return rows. For increased performance,ExecuteReader invokes commands using the Transact-SQL sp_executesqlsystem stored procedure. Therefore, ExecuteReader might not have the effect that you want if used to execute commands such as Transact-SQL SET statements.
ExecuteNonQueryExecutes commands such as Transact-SQL INSERT, DELETE, UPDATE, and SET statements.
ExecuteScalarRetrieves a single value (for example, an aggregate value) from a database.
ExecuteXmlReaderSends 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.


TopicLocation
Walkthrough: Displaying Hierarchical Data in a TreeView ControlBuilding ASP .NET Web Applications in Visual Studio
Walkthrough: Displaying Hierarchical Data in a TreeView ControlBuilding ASP .NET Web Applications in Visual Studio
Walkthrough: Displaying Hierarchical Data in a TreeView ControlBuilding ASP .NET Web Applications in Visual Studio
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();
        }
    }
}






No comments :

Post a Comment