Mega Code Archive

 
Categories / C# / ADO Database
 

Get row count by ExecuteScalar

using System; using System.Data; using System.Data.SqlClient;    class CommandExampleScalar    {       static void Main()        {          SqlConnection thisConnection = new SqlConnection("server=(local)\\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI");          SqlCommand thisCommand = new SqlCommand("SELECT COUNT(*) FROM Employee", thisConnection);          try {             thisConnection.Open();             Console.WriteLine("Number of Employees is: {0}",                thisCommand.ExecuteScalar());          }          catch (SqlException ex)           {             Console.WriteLine(ex.ToString());          }          finally           {             thisConnection.Close();             Console.WriteLine("Connection Closed.");          }       }    }