Create SqlCommand with both sql query and connection : SqlCommand : ADO.Net C# Examples


C# Examples » ADO.Net » SqlCommand »

 

Create SqlCommand with both sql query and connection









    
using  System;
using  System.Data;
using  System.Data.SqlClient;

class  CommandScalar
{
      static  void  Main()
      {
            SqlConnection  conn  =  new  SqlConnection("server=(local)\\SQLEXPRESS;database=MyDatabase;Integrated  Security=SSPI;");

            string  sql  =  @"select  count(*)  from  employee";

            SqlCommand  cmd  =  new  SqlCommand(sql,  conn);
            Console.WriteLine("Command  created  and  connected.");

            try
            {
                  conn.Open();

                  Console.WriteLine("Number  of  Employees  is  {0}",  cmd.ExecuteScalar());
            }
            catch  (SqlException  ex)
            {
                  Console.WriteLine(ex.ToString());
            }
            finally
            {
                  conn.Close();
                  Console.WriteLine("Connection  Closed.");
            }
      }
}
    
   
  
   



Output

Command created and connected.
Number of Employees is 4
Connection Closed.


HTML code for linking to this page:

Follow Navioo On Twitter

C# Examples

 Navioo ADO.Net
» SqlCommand