asp.net.ph

IDbCommand.ExecuteScalar Method

System.Data Namespace   IDbCommand 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 ( );

[ JScript ]
public function ExecuteScalar ( ) : Object;

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 database. 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 IDataReader.

Example

The following example demonstrates using the ExecuteScalar method.

protected void ExecuteScalarDemo ( ) {
   // specify the data source
   SqlConnection myConn = new SqlConnection (
      "server=( local )\\NetSDK; trusted_connection=yes; database=pubs" );

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

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

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

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

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

 Show me 

See Also

IDbCommand 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