PreviousData Provider for .NET Guide (9.1 revision 1) Next

Retrieving a Scalar Value

Show this topic in Library frames

You can use the ExecuteScalar method of the Command object to return a single value, such as a sum or a count, from the database. The ExecuteScalar method returns the value of the first column of the first row of the result set.

The following code example, which requires the emp table (see Sample Tables for Pervasive.SQL ), shows how to retrieve the count of a specified group:

// Retrieve the number of employees who make more than 
$50000 
// from the emp table 
// Open connection to Pervasive.SQL database 
PsqlConnection  Conn; 
Conn = new PsqlConnection("ServerDSN=DEMODATA; 
								UID=test; 
								PWD=test; 
                           Server=localhost"); 
Conn.Open(); 
// Make a command object  
PsqlCommand  salCmd = new PsqlCommand("select count(sal) 
from emp where sal>'50000'",Conn); 
try 
{ 
    int count = (int)salCmd.ExecuteScalar(); 
} 
catch (Exception ex)  
{ 
    // Display any exceptions in a messagebox 
    MessageBox.Show (ex.Message); 
} 
//  Close the connection 
Conn.Close(); 

Chapter contents
Publication contents

Prev topic: Retrieving Data Using a DataReader
Next topic: Using a Local Transaction