ExecuteScalar Method

MySQL Connector.Net

Collapse image Expand Image Copy image CopyHover image
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.

Namespace: MySql.Data.MySqlClient
Assembly: MySql.Data (in MySql.Data.dll) Version: 6.8.4.0

Syntax

C#
public override Object ExecuteScalar()
Visual Basic
Public Overrides Function ExecuteScalar As Object
Visual C++
public:
virtual Object^ ExecuteScalar() override

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 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 a MySqlDataReader

Examples

The following example creates a MySqlCommand and then executes it using ExecuteScalar. The example is passed a string that is a SQL statement that returns an aggregate result, and a string to use to connect to the data source.
Visual Basic Copy imageCopy
Public Sub CreateMySqlCommand(myScalarQuery As String, myConnection As MySqlConnection)
Dim myCommand As New MySqlCommand(myScalarQuery, myConnection)
myCommand.Connection.Open()
myCommand.ExecuteScalar()
myConnection.Close()
End Sub
C# Copy imageCopy
public void CreateMySqlCommand(string myScalarQuery, MySqlConnection myConnection)
{
MySqlCommand myCommand = new MySqlCommand(myScalarQuery, myConnection);
myCommand.Connection.Open();
myCommand.ExecuteScalar();
myConnection.Close();
}
Visual C++ Copy imageCopy
public:
void CreateMySqlCommand(String* myScalarQuery, MySqlConnection* myConnection)
{
MySqlCommand* myCommand = new MySqlCommand(myScalarQuery, myConnection);
myCommand->Connection->Open();
myCommand->ExecuteScalar();
myConnection->Close();
}

See Also