You need to return a value from the SQL query, such as the number of records in the table. You can use the ExecuteScalar () method. This method returns only one value. The following shows the console application code:
Using System. Data;
Using System. Data. SqlClient;
Namespace ExecuteScalar
{
Class Program
{
Static void Main (string [] args)
{
SqlConnection thisConnection = new SqlConnection (
@ "Data Source = scott; Initial Catalog = northwind; Persist Security Info = True; User ID = sa; Password = sa123 ");
ThisConnection. Open ();
SqlCommand thisCommand = thisConnection. CreateCommand ();
ThisCommand. CommandText = "select count (*) from MERs ";
// ExecuteScalar: Execute an SQL command that returns only one value.
Object countResult = thisCommand. ExecuteScalar ();
Console. WriteLine ("Count of MERs = {0}", countResult );
Console. ReadLine ();
ThisConnection. Close ();
}
}
}
Result:
Count of MERs = 91