Advertisement
WindFell

Ado Net Transaction

Apr 5th, 2019
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.17 KB | None | 0 0
  1. using System;
  2. using System.Data;
  3. using System.Data.SqlClient;
  4. using System.Linq;
  5.  
  6. namespace CallStoreProcedure
  7. {
  8.     class StartUp
  9.     {
  10.         static void Main(string[] args)
  11.         {
  12.             string connectionString = @"Data Source=localhost\SQLEXPRESS;Initial Catalog=Geography;Integrated Security=True";
  13.             string procedure = "usp_ReturnMountainsWithCountryCurrencyCode";
  14.  
  15.             DataTable table = new DataTable();
  16.  
  17.             using (SqlConnection connection = new SqlConnection(connectionString))
  18.             {
  19.                 connection.Open();
  20.  
  21.                 SqlCommand command = connection.CreateCommand();
  22.                 SqlTransaction transaction;
  23.  
  24.                 transaction = connection.BeginTransaction("ExecuteProcedure");
  25.                 command.CommandType = CommandType.StoredProcedure;
  26.                 command.Connection = connection;
  27.                 command.Transaction = transaction;
  28.  
  29.                 try
  30.                 {
  31.                     command.CommandText = procedure;
  32.  
  33.                     using (var reader = command.ExecuteReader())
  34.                     {
  35.                         table.Load(reader);
  36.                     }
  37.  
  38.                     transaction.Commit();
  39.                 }
  40.                 catch (Exception ex)
  41.                 {
  42.                     Console.WriteLine("Commit Exception Type: {0}", ex.GetType());
  43.                     Console.WriteLine("Message: {0}", ex.Message);
  44.  
  45.                     try
  46.                     {
  47.                         transaction.Rollback();
  48.                     }
  49.                     catch (Exception ex2)
  50.                     {
  51.                         Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
  52.                         Console.WriteLine("Message: {0}", ex2.Message);
  53.                     }
  54.                 }
  55.             }
  56.  
  57.             var result = table
  58.                 .AsEnumerable()
  59.                 .Select(r => $"{r["MountainRange"]} - {r["Currency Code"]}")
  60.                 .ToList();
  61.             Console.WriteLine("MountainRange - Currency Code");
  62.             Console.WriteLine(string.Join(Environment.NewLine, result));
  63.         }
  64.     }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement