All pastes #145710 Raw Edit

Miscellany

public text v1 · immutable
#145710 ·published 2006-08-23 04:02 UTC
rendered paste body
 using System;
 using System.Data;
 using System.Data.SqlClient;
 
 namespace CommandExampleNonQuery
 {
 	class CommandExampleNonQuery
 	{
 		static void Main()
 		{
 			SqlConnection conn = new SqlConnection( @"Server=(local)\NetSDK;" +
 			                                       "Integrated Security=SSPI;" +
 			                                       "Database=Northwind;" );
 			
 			SqlCommand selectCommand = new SqlCommand( "SELECT COUNT(*) FROM Employees", conn );
 			SqlCommand nonQueryCommand = conn.CreateCommand();
 			
 			try
 			{
 				conn.Open();
 				Console.WriteLine( "Connection open" );
 				
 				Console.WriteLine( "Before INSERT: Number of employees is: {0}", selectCommand.ExecuteScalar() );
 				
 				nonQueryCommand.CommandText = "INSERT INTO Employees (FirstName, LastName) " +
 					"VALUES ('Zachariah', 'Zinn' )";
 				Console.WriteLine( nonQueryCommand.CommandText );
 				Console.WriteLine( "Number of rows affected is: {0}", nonQueryCommand.ExecuteNonQuery() );
 				
 				Console.WriteLine( "After INSERT: Number of employees is: {0}", selectCommand.ExecuteScalar() );
 				
 				nonQueryCommand.CommandText = "DELETE FROM Employees WHERE LastName = 'Zinn' AND FirstName = 'Zachariah'";
 				Console.WriteLine( nonQueryCommand.CommandText );
 				Console.WriteLine( "Number of rows affected is: {0}", nonQueryCommand.ExecuteNonQuery() );
 				Console.WriteLine( "After DELETE: Number of employees is: {0}", selectCommand.ExecuteScalar() );
 			}
 			catch (SqlException ex )
 			{
 				Console.WriteLine( "Error: " + ex.Message );
 			}
 			finally
 			{
 				if( conn.State = ConnectionState.Open )
 				{
 					conn.Close();
 					Console.WriteLine( "Connection closed" );
 				}
 			}
 			Console.ReadLine();
 		}
 	}
 }