Executing a command using ExecuteNonQuery

ExecuteNonQuery executes a command and returns the number of records affected. There are six overloaded methods available to meet different needs such as executing an Sql query, a stored procedure, a stored procedure with parameter values, with transaction, and so on.

The following code snippet shows the usage of the ExecuteNonQuery method and the retrieval of the output parameter value:

//Step 1: Create Default Database instance
Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>();
//Step 2: Create Database Command - Stored Procedure
DbCommand dbCommand = db.GetStoredProcCommand("usp_insert_Customer");
//Step 3: Add Input Parameters
db.AddInParameter(dbCommand, "FirstName", DbType.String, "John");
db.AddInParameter(dbCommand, "LastName", DbType.String, "Lennon");
//Step 4: Add Output Parameter
db.AddOutParameter(dbCommand, "CustomerID", DbType.Int32, int.MaxValue);
//Step 5: Execute Query
int numberOfRecordsAffected = db.ExecuteNonQuery(dbCommand);
if (numberOfRecordsAffected > 0)
{
//Step 6: Retrieve Output Parameter Value
int customerID = (int)db.GetParameterValue(dbCommand, "CustomerID");
}

This code snippet demonstrates a typical usage of ExecuteNonQuery where a stored procedure is used to insert a record and we retrieve the primary key value as part of the value of output parameter.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.144.65