Retrieving scalar values

One of the common requirements while working with databases is to retrieve a single value. The ExecuteScalar method provides the ability to execute a command or a query and returns the value of the first column of the first record. Similar to other execute methods, the ExecuteScalar method contains six overloads satisfying several different scenarios.

The following code snippet shows the retrieval of scalar value using the ExecuteScalar method:

//Step 1: Create Default Database instance
Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>();
//Step 2: Create Database Command - SQL String
DbCommand dbCommand = db.GetSqlStringCommand("SELECT COUNT(*) FROM Customers");
//Step 3: Execute Query
int totalCustomers = (int)db.ExecuteScalar(dbCommand);

The previous code block demonstrates the typical usage of the ExecuteScalar method that retrieves the total record count for a specific Sql query.

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

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