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 Th
e 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 Th
e 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.
Name | Description |
---|---|
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:
A typical ExecuteScalar query can be formatted as in the following C# example:
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 SqlConnec tion("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.
Assembly: System.Data (in System.Data.dll)
The SqlCommand type exposes the following members.
Name | Description | |
---|---|---|
SqlCommand() | Initializes a new instance of the SqlCommand class. | |
SqlCommand(String) | Initializes a new instance of the SqlCommand class with the text of the query. | |
SqlCommand(String, SqlConnection) | Initializes a new instance of the SqlCommand class with the text of the query and a SqlConnection. | |
SqlCommand(String, SqlConnection, SqlTransaction) | Initializes a new instance of the SqlCommand class with the text of the query, a SqlConnection, and the SqlTransaction. |
Name | Description | |
---|---|---|
CanRaiseEvents | Gets a value indicating whether the component can raise an event. (Inherited from Component.) | |
CommandText | Gets or sets the Transact-SQL statement, table name or stored procedure to execute at the data source. (OverridesDbCommand.Co | |
CommandTimeout | Gets or sets the wait time before terminating the attempt to execute a command and generating an error. (OverridesDbCommand.Com | |
CommandType | Gets or sets a value indicating how the CommandText property is to be interpreted. (Overrides DbComm | |
Connection | Gets or sets the SqlConnection used by this instance of theSqlCommand. | |
Container | Gets the IContainer that contains the Component. (Inherited from Component.) | |
DbConnection | Gets or sets the DbConnection used by this DbCommand.(Inherited from DbCommand.) | |
DbParameterCollection | Gets the collection of DbParameter objects. ( | |
DbTransaction | Gets or sets the DbTransaction within which this DbCommandobject executes. (Inherited from DbCommand.) | |
DesignMode | Gets a value that indicates whether the Component is currently in design mode. (Inherited from Component.) | |
DesignTimeVisible | Gets or sets a value indicating whether the command object should be visible in a Windows Form Designer control. (OverridesDbCommand.D | |
Events | Gets the list of event handlers that are attached to thisComponent. (Inherited from Component.) | |
Notification | Gets or sets a value that specifies the SqlNotificationRequestobje | |
NotificationAutoEnlist | Gets or sets a value indicating whether the application should automatically receive query notifications from a commonSqlDependency object. | |
Parameters | Gets the SqlParameterCollection. | |
Site | Gets or sets the ISite of the Component. (Inherited fromComponent.) | |
Transaction | Gets or sets the SqlTransaction within which the SqlCommandexecutes. | |
UpdatedRowSource | Gets or sets how command results are applied to the DataRowwhen used by the Update method of the DbDataAdapter.(Overrides D |
Name | Description | |
---|---|---|
BeginExecuteNonQuery() | Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this SqlCommand. | |
BeginExecuteNonQuery( | 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. | |
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. | |
BeginExecuteReader( | Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this SqlCommand using one of the CommandBehavior values. | |
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, given a callback procedure and state information. | |
BeginExecuteReader( | 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. | |
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. | |
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, using a callback procedure. | |
Cancel | Tries to cancel the execution of aSqlCommand. (Overrides DbComm | |
Clone | Creates a new SqlCommand object that is a copy of the current instance. | |
CreateDbParameter | Creates a new instance of a DbParameterobject. ( | |
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.) | |
CreateParameter | Creates a new instance of a SqlParameterobject. | |
Dispose() | Releases all resources used by the Component.(Inherited from Component.) | |
Dispose(Boolean) | Releases the unmanaged resources used by theComponent and optionally releases the managed resources. (Inherited fromComponent.) | |
EndExecuteNonQuery | Finishes asynchronous execution of a Transact-SQL statement. | |
EndExecuteReader | Finishes asynchronous execution of a Transact-SQL statement, returning the requested SqlDataReader. | |
EndExecuteXmlReader | Finishes asynchronous execution of a Transact-SQL statement, returning the requested data as XML. | |
Equals(Object) | Determines whether the specified Object is equal to the current Object. (Inherited fromObject.) | |
ExecuteDbDataReader | Executes the command text against the connection. (Inherited from DbCommand.) | |
ExecuteNonQuery | Executes a Transact-SQL statement against the connection and returns the number of rows affected. (OverridesDbCommand. | |
ExecuteReader() | Sends the CommandText to the Connectionand builds a SqlDataReader. | |
ExecuteReader(CommandBehavior) | Sends the CommandText to the Connection, and builds a SqlDataReader using one of theCommandBehavior values. | |
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. (OverridesDbCommand.E | |
ExecuteXmlReader | Sends the CommandText to the Connectionand builds an XmlReader object. | |
Finalize | Releases unmanaged resources and performs other cleanup operations before the Componentis reclaimed by garbage collection. (Inherited from Component.) | |
GetHashCode | Serves as a hash function for a particular type.(Inherited from Object.) | |
GetLifetimeService | Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.) | |
GetService | Returns an object that represents a service provided by the Component or by its Container.(Inherited from Component.) | |
GetType | Gets the Type of the current instance.(Inherited from Object.) | |
InitializeLifetimeService | Obtains a lifetime service object to control the lifetime policy for this instance. (Inherited fromMarshalByRefObject.) | |
MemberwiseClone() | Creates a shallow copy of the current Object.(Inherited from Object.) | |
MemberwiseClone(Boolean) | Creates a shallow copy of the currentMarshalByRefObject | |
Prepare | Creates a prepared version of the command on an instance of SQL Server. (OverridesDbCommand.Pr | |
ResetCommandTimeout | Resets the CommandTimeout property to its default value. | |
ToString | Returns a String containing the name of theComponent, if any. This method should not be overridden. (Inherited from Component.) |
Name | Description | |
---|---|---|
Disposed | Occurs when the component is disposed by a call to the Disposemethod. (Inherited from Component.) | |
StatementCompleted | Occurs when the execution of a Transact-SQL statement completes. |
Name | Description | |
---|---|---|
ICloneable.Clone | Creates a new SqlCommand object that is a copy of the current instance. | |
IDbCommand.Connection | Gets or sets the IDbConnection used by this instance of the IDbCommand.(Inherited from DbCommand.) | |
IDbCommand.CreateParameter | Creates a new instance of anIDbDataParameter object. ( | |
IDbCommand.ExecuteReader() | Executes the CommandText against the Connection and builds anIDataReader. (Inherited fromDbCommand.) | |
IDbCommand.ExecuteReader( | Executes the CommandText against the Connection, and builds anIDataReader using one of theCommandBehavior values. ( | |
IDbCommand.Parameters | Gets the IDataParameterCollection.( | |
IDbCommand.Transaction | Gets 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:
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.
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 toEndExecuteNonQuery 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 toBeginExecuteXmlReader must be paired with a call to EndExecuteXmlReader, which finishes the operation, typically on a separate thread, and returns anXmlReader object. |
ExecuteReader | Executes commands that return rows. For increased performance,ExecuteReader |
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.
Topic | Location |
---|---|
Walkthrough: Displaying Hierarchical Data in a TreeView Control | Building ASP .NET Web Applications in Visual Studio |
Walkthrough: Displaying Hierarchical Data in a TreeView Control | Building ASP .NET Web Applications in Visual Studio |
Walkthrough: Displaying Hierarchical Data in a TreeView Control | Building 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