Create SqlCommand object : SqlConnection « Database ADO.net « C# / C Sharp






Create SqlCommand object


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

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

         SqlCommand thisCommand = new SqlCommand();
         Console.WriteLine("Command created.");

         try {
            thisConnection.Open();

            thisCommand.Connection = thisConnection;
 
            thisCommand.CommandText = "SELECT COUNT(*) FROM Employee";
            Console.WriteLine("Ready to execute SQL command: {0}", thisCommand.CommandText);
         } catch (SqlException ex) {
            Console.WriteLine(ex.ToString());
         } finally {
            thisConnection.Close();
            Console.WriteLine("Connection Closed.");
         }
      }
   }


           
       








Related examples in the same category

1.SqlConnection propertiesSqlConnection properties
2.WorkstationId
3.ConnectionTimeout
4.PacketSize
5.Connection String
6.DataSource
7.SqlConnection state change event
8.SqlConnection: info message event handler
9.Connect to Access database
10.Creating SQL Connections