Advertisement
Guest User

Connection SQL using C#

a guest
Mar 14th, 2016
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 5.39 KB | None | 0 0
  1. using System;
  2. using System.Configuration;
  3. using System.Data;
  4. using System.Data.SqlClient;
  5.  
  6. namespace PruebaDB
  7. {
  8.     class Program
  9.     {
  10.         static void Main(string[] args)
  11.         {
  12.             var arrayIds = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
  13.  
  14.             Console.WriteLine("============== INSERTANDO REGISTROS EN LA BD =============");
  15.            
  16.  
  17.             string name = "John {0}", lastname = "Doe {0}", address = "Dirección {0}.";
  18.             foreach (var id in arrayIds)
  19.             {
  20.                 var item = new Item()
  21.                 {
  22.                     Name = string.Format(name, id),
  23.                     LastName = string.Format(lastname, id),
  24.                     Address = (id%2) > 0 ? string.Format(address,id):null
  25.                 };
  26.                 AddItem(item);
  27.             }
  28.             Console.WriteLine("...Listo.");
  29.  
  30.  
  31.             Console.WriteLine("\n============== LEYENDO DATOS DE LA BD =============");
  32.  
  33.             foreach (var id in arrayIds)
  34.             {
  35.                 var item = GetItemById(id);
  36.                 if(item != null)
  37.                 {
  38.                     Console.WriteLine("Id:{0} | Name: {1} | LastName: {2} | Address:{3}",
  39.                                         item.Id, item.Name, item.LastName, item.Address);
  40.                 }
  41.  
  42.             }
  43.             Console.WriteLine("...Listo.");
  44.             Console.WriteLine("\n============= Limpiando Tabla (truncate) =============");
  45.  
  46.             TruncateTable();
  47.  
  48.             Console.WriteLine("...Listo.");
  49.  
  50.  
  51.             Console.ReadKey();
  52.         }
  53.  
  54.         private static void AddItem(Item item)
  55.         {
  56.             if (item == null) throw new ArgumentNullException("item");
  57.  
  58.             try
  59.             {
  60.                 var connString = ConfigurationManager.ConnectionStrings["TESTDBConnection"].ConnectionString;
  61.                 var sqlCommand = "INSERT INTO Item(Name, LastName, Address) VALUES(@Name, @LastName, @Address)";
  62.  
  63.                 using (var connection = new SqlConnection(connString))
  64.                 {
  65.                     using (var command = new SqlCommand(sqlCommand, connection))
  66.                     {
  67.                         command.Parameters.Add("@Name", SqlDbType.NVarChar).Value = item.Name;
  68.                         command.Parameters.Add("@LastName", SqlDbType.NVarChar).Value = item.LastName;
  69.                         if(string.IsNullOrEmpty(item.Address))
  70.                             command.Parameters.Add("@Address", SqlDbType.NVarChar).Value = DBNull.Value;
  71.                         else
  72.                             command.Parameters.Add("@Address", SqlDbType.NVarChar).Value = item.Address;
  73.  
  74.                         connection.Open();
  75.                         command.ExecuteNonQuery();
  76.                     }
  77.                 }
  78.  
  79.             }
  80.             catch
  81.             {
  82.                 throw;
  83.             }
  84.         }
  85.  
  86.         //EJECUTANDO A UN STORE PROCEDURE
  87.         private static Item GetItemById(int itemId)
  88.         {
  89.             try
  90.             {
  91.                 Item retrievedItem = null;
  92.  
  93.                 var connString = ConfigurationManager.ConnectionStrings["TESTDBConnection"].ConnectionString;
  94.                 var sqlCommand = "sp_GetItemById";
  95.  
  96.                 using (var connection = new SqlConnection(connString))
  97.                 {
  98.                     using (var command = new SqlCommand(sqlCommand, connection))
  99.                     {
  100.                         command.CommandType = CommandType.StoredProcedure;
  101.                         command.Parameters.Add("@ItemId", SqlDbType.Int).Value = itemId;
  102.  
  103.                         connection.Open();
  104.                         var reader = command.ExecuteReader();
  105.  
  106.                         if (!reader.HasRows)
  107.                             return retrievedItem;
  108.                         else
  109.                             retrievedItem = new Item();
  110.  
  111.                         while (reader.Read())
  112.                         {
  113.                             retrievedItem.Id = Convert.ToInt32(reader["Id"]);
  114.                             retrievedItem.Name = reader["Name"] as string;
  115.                             retrievedItem.LastName = reader["LastName"] as string;
  116.                             retrievedItem.Address = reader["Address"] as string;
  117.                         }
  118.                         return retrievedItem;
  119.                     }
  120.                 }
  121.  
  122.             }
  123.             catch
  124.             {
  125.                 throw;
  126.             }
  127.         }
  128.        
  129.  
  130.         private static void TruncateTable()
  131.         {
  132.             try
  133.             {
  134.                 var connString = ConfigurationManager.ConnectionStrings["TESTDBConnection"].ConnectionString;
  135.                 var sqlCommand = "TRUNCATE TABLE Item";
  136.  
  137.                 using (var connection = new SqlConnection(connString))
  138.                 {
  139.                     using (var command = new SqlCommand(sqlCommand, connection))
  140.                     {
  141.                         connection.Open();
  142.                         command.ExecuteNonQuery();
  143.                     }
  144.                 }
  145.  
  146.             }
  147.             catch
  148.             {
  149.                 throw;
  150.             }
  151.         }
  152.     }//program.cs
  153.  
  154.     public class Item
  155.     {
  156.         public int Id { get; set; }
  157.         public string Name { get; set; }
  158.         public string LastName { get; set; }
  159.         public string Address { get; set; }
  160.  
  161.     }
  162. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement