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;
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 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.
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 ( );
}
protected sub ExecuteScalarDemo ( )
' specify the data source
dim myConn as new SqlConnection ( _
"server=( local )\NetSDK; trusted_connection=yes; database=pubs" )
' 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 myCmd as new SqlCommand ( query, myConn )
' open the data connection
myConn.Open ( )
' execute the command
dim count as int = Ctype ( myCmd.ExecuteScalar ( ), int )
' close the data connection
myConn.Close ( )
end sub |
|
C# |
VB |
Show me
IDbCommand Members