Joel.Net.DatabaseUtility.dll Class Library

DatabaseUtility.ExecuteScalar Method (String)

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]
Shared  OverloadsPublic Function ExecuteScalar( _ 
   ByVal commandText As String _ 
) As Object
[C#]
public static object ExecuteScalar(
   string commandText
);
[C++]
public: static Object* ExecuteScalar(
   String* commandText
);
[JScript]
public static function ExecuteScalar(
   String commandText
): Object;

Parameters

commandText
The text of the query.

Return Value

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

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 SqlDataReader.

Example

[C#, Visual Basic] The following example creates a SqlCommand and then executes it using ExecuteScalar. The example is passed a string that is a Transact-SQL statement that returns an aggregate result.

[C#]
DatabaseUtility.Connection = new SqlConnection("Server=127.0.0.1;Database=Northwind;Uid=sa;Pwd=;");

string customerName = DatabaseUtility.ExecuteScalar("SELECT CustomerName FROM Customers WHERE CustomerID = 'ALFKI'");
[Visual Basic]
DatabaseUtility.Connection = New SqlConnection("Server=127.0.0.1;Database=Northwind;Uid=sa;Pwd=;")

Dim customerName As String = DatabaseUtility.ExecuteScalar("SELECT CustomerName FROM Customers WHERE CustomerID = 'ALFKI'")

See Also

DatabaseUtility Class | Joel.Net Namespace | DatabaseUtility.ExecuteScalar Overload List