asp.net.ph

OleDbCommand.ExecuteScalar Method

System.Data.OleDb Namespace   OleDbCommand Class


Executes the query, and returns the first column of the first row in the resultset returned by the query. Extra columns or rows are ignored.

[ VB ]
NotOverridable Public Function ExecuteScalar ( ) As Object

[ C# ]
public object ExecuteScalar ( );

[ C++ ]
public: __sealed Object* ExecuteScalar ( );

[ C++ ]
public function ExecuteScalar ( ) : Object;

Implements

IDbCommand.ExecuteScalar

Return Value

The first column of the first row in the resultset.

Remarks

Use the ExecuteScalar method to retrieve a single value ( for example, an aggregate value ) from a data source. This requires less code than using the ExecuteReader method, and then performing the operations necessary to generate the single value using the data returned by an OleDbDataReader.

A typical ExecuteScalar query can be formatted as in the following C# example:

CommandText = "SELECT count ( * ) as NumberOfRegions from region";
Int count = ( int ) ExecuteScalar ( );

Example

The following example demonstrates using the ExecuteScalar method.

protected void ExecuteScalarDemo ( ) {
   // specify the data source
   OleDbConnection myConn = new OleDbConnection (
      "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + 
      Server.MapPath ( "~/app_data/pubs.mdb" ) );

   // define the command query
   string query = "SELECT COUNT ( * ) FROM Authors WHERE State='CA'";

   // initialize command object with the specified query and connection
   OleDbCommand myCommand = new OleDbCommand ( query, myConn );

   // open the data connection
   myConn.Open ( );

   // execute the command
   int count = ( int ) myCommand.ExecuteScalar ( );

   // close the data connection
   myConn.Close ( );
}
  C# VB

 Show me 

See Also

OleDbCommand Members Skip Navigation Links




Home
Suggested Reading


Previous page Back to top Next page

© 2000-2010 Rey Nuñez All rights reserved.

If you have any question, comment or suggestion
about this site, please send us a note

You can help support asp.net.ph