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.
[Visual Basic]
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 from the data returned by a DB2®DataReader .
A typical ExecuteScalar query can be formatted as in the following C# example:
CommandText = "select count(*) as NumberOfEmployee from EMPLOYEE";
Int count = (int) ExecuteScalar();
[Visual Basic, C#] The following example creates a DB2Command and then executes it using ExecuteScalar. The example is passed a string that is an SQL statement that returns an aggregate result, and a string to use to connect to the database.
[Visual Basic]
Public Sub CreateMyDB2Command(myScalarQuery As String,
myConnection As DB2Connection)
Dim myCommand As New DB2Command(myScalarQuery, myConnection)
myCommand.Connection.Open()
Dim qryValue As object = myCommand.ExecuteScalar()
myConnection.Close()
End Sub 'CreateMyDB2Command
[C#]
public void CreateMyDB2Command(string myScalarQuery, DB2Connection myConnection)
{
DB2Command myCommand = new DB2Command(myScalarQuery, myConnection);
myCommand.Connection.Open();
object qryValue = myCommand.ExecuteScalar();
myConnection.Close();
}