Archive for the tag 'c#'

Executing a SQL Server stored procedure in C#

Are you kidding me? I’m a major amatuer at anything .NET, and after some Googling and about 15 minutes of coding, this works. How ridiculously easy.

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Data;
  5. using System.Data.SqlClient;
  6.  
  7. namespace ExecuteStoredProcedure
  8. {
  9. class Program
  10. {
  11. static void Main(string[] args)
  12. {
  13. SqlConnection conn;
  14. try
  15. {
  16. conn = new SqlConnection("server=server;database=db;Trusted_Connection=yes");
  17. conn.Open();
  18. Console.WriteLine("Connection successful…");
  19. }
  20. catch (Exception ex)
  21. {
  22. Console.WriteLine(ex.Message);
  23. return;
  24. }
  25.  
  26. SqlCommand db_cmd = new SqlCommand("dbo.usp_c_sharp_test",conn);
  27. db_cmd.CommandType = CommandType.StoredProcedure;
  28.  
  29. SqlDataReader data_reader;
  30. data_reader = db_cmd.ExecuteReader();
  31. data_reader.Close();
  32. conn.Close();
  33. }
  34. }
  35. }