Export (0) Print
Expand All

OdbcCommand.ExecuteScalar Method

Note: This namespace, class, or member is supported only in version 1.1 of the .NET Framework.

Executes the query, and returns the first column of the first row in the result set returned by the query. Extra columns or rows are ignored.

[Visual Basic]
Public Overridable Function ExecuteScalar() As Object Implements _
   IDbCommand.ExecuteScalar
[C#]
public virtual object ExecuteScalar();
[C++]
public: virtual Object* ExecuteScalar();
[JScript]
public function ExecuteScalar() : Object;

Return Value

The first column of the first row in the result set, or a null reference if the result set is empty.

Implements

IDbCommand.ExecuteScalar

Remarks

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 from the data returned by an OdbcDataReader.

A typical ExecuteScalar query can be formatted as in the following C# example:

CommandText = "select count(*) from region";
Int32 count = (int32) ExecuteScalar();

Example

[Visual Basic, C#, C++] The following example creates an OdbcCommand 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 data source.

[Visual Basic] 
Public Sub CreateMyOdbcCommand(myScalarQuery As String, myConnection As OdbcConnection)
    Dim myCommand As New OdbcCommand(myScalarQuery, myConnection)
    myCommand.Connection.Open()
    myCommand.ExecuteScalar()
    myConnection.Close()
End Sub 'CreateMyOdbcCommand

[C#] 
public void CreateMyOdbcCommand(string myScalarQuery, OdbcConnection myConnection) 
 {
    OdbcCommand myCommand = new OdbcCommand(myScalarQuery, myConnection);
    myCommand.Connection.Open();
    myCommand.ExecuteScalar();
    myConnection.Close();
 }

[C++] 
public:
    void CreateMyOdbcCommand(String* myScalarQuery, OdbcConnection* myConnection)
    {
        OdbcCommand* myCommand = new OdbcCommand(myScalarQuery, myConnection);
        myCommand->Connection->Open();
        myCommand->ExecuteScalar();
        myConnection->Close();
    };

[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.

Requirements

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family

See Also

OdbcCommand Class | OdbcCommand Members | System.Data.Odbc Namespace

Show:
© 2014 Microsoft