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;
IDbCommand.ExecuteScalar
The first column of the first row in the resultset.
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 ( );
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 ( );
}
protected sub ExecuteScalarDemo ( )
' specify the data source
dim myConn as new OleDbConnection ( _
"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & _
Server.MapPath ( "~/app_data/pubs.mdb" ) )
' define the command query
dim query as string = "SELECT COUNT ( * ) FROM Authors WHERE State='CA'"
' initialize command object with the specified query and connection
dim myCommand as new OleDbCommand ( query, myConn )
' open the data connection
myConn.Open ( )
' execute the command
dim count as int = Ctype ( myCommand.ExecuteScalar ( ), int )
' close the data connection
myConn.Close ( )
end sub |
|
C# |
VB |
Show me
OleDbCommand Members