Advertisement
NAK

ExecuteSqlDataReader Program (C#)

NAK
Dec 4th, 2013
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 5.81 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Data.SqlClient;
  5. using System.Linq;
  6. using System.Text;
  7.  
  8. namespace ConsoleApplication1
  9. {
  10.     class Program
  11.     {
  12.         static void Main(string[] args)
  13.         {
  14.             // not using any Params for this example but left it in
  15.             List<Parameter> Params = new List<Parameter>();
  16.             // Get our first list of data
  17.             List<TestClass_1> testlist1 = new List<TestClass_1>();
  18.             testlist1 = ExecuteSqlDataReader<TestClass_1>("<your SQL query here>", "<your SQL connection here>", Params);
  19.             // Get our second list of data
  20.             List<TestClass_2> testlist2 = new List<TestClass_2>();
  21.             testlist2 = ExecuteSqlDataReader<TestClass_2>("<your SQL query here>", "<your SQL connection here>", Params);
  22.         }
  23.  
  24.         /// <summary>
  25.         /// Generic function that uses SqlClient to connect and retrieve data from a DB
  26.         /// </summary>
  27.         /// <typeparam name="T"></typeparam>
  28.         /// <param name="SQLText"></param>
  29.         /// <param name="SQLConnectionStrong"></param>
  30.         /// <param name="Params"></param>
  31.         /// <returns>Return a collection of T </returns>
  32.         /// <remarks></remarks>
  33.         public static List<T> ExecuteSqlDataReader<T>(string SQLText, string SQLConnectionStrong, List<Parameter> Params)
  34.         {
  35.             List<T> ListOfT = new List<T>();
  36.  
  37.             using (SqlConnection SQLcon =new SqlConnection(SQLConnectionStrong))
  38.             {
  39.                 using (SqlCommand SQLCMD =new SqlCommand(SQLText, SQLcon))
  40.                 {
  41.                     SQLCMD.CommandText = SQLText;          // set the SQL command (SP or in line SQL)
  42.                     SQLCMD.CommandType = CommandType.Text;       // set the command type (StoredProcedure or Text)
  43.                     //SQLCMD.CommandTimeout = mySQLSection.CommandTimeout; // set the command time out
  44.  
  45.                     foreach (Parameter p in Params)
  46.                     {
  47.                         SQLCMD.Parameters.AddWithValue(p.Name, p.Value);
  48.                     }
  49.  
  50.                     if(SQLcon.State == ConnectionState.Closed)
  51.                     {
  52.                         SQLcon.Open(); // open the connection
  53.                     }
  54.  
  55.                     using (SqlDataReader myReader = SQLCMD.ExecuteReader())                    // create the Data Reader and get the Data
  56.                     {
  57.                         DataTable dt = myReader.GetSchemaTable();         // Get the Table Schema (Needed to identify each column type)
  58.  
  59.                         while(myReader.Read()) // for each record in the data set
  60.                         {
  61.                             T tmp = CreateInstanceOf_T<T>(); // create an instance of T
  62.                             int index = 0;    // reset the column indexer
  63.  
  64.                             foreach(DataRow row in dt.Rows)                              // for each column in the table
  65.                             {
  66.                                 var v = typeof(T).GetProperty(row[0].ToString());    // get the type
  67.                                 try
  68.                                 {
  69.                                     if (v != null)
  70.                                     {
  71.                                         switch (v.PropertyType.ToString())
  72.                                         {
  73.                                             case "System.Int32":
  74.                                                 typeof(T).GetProperty(row[0].ToString()).SetValue(tmp, myReader.GetInt32(index));       // to Int32
  75.                                                 break;
  76.                                             case "System.Guid":
  77.                                                 typeof(T).GetProperty(row[0].ToString()).SetValue(tmp, myReader.GetGuid(index));        // to Guid
  78.                                                 break;
  79.                                             case "System.String":
  80.                                                 if(!myReader.IsDBNull(index))
  81.                                                     typeof(T).GetProperty(row[0].ToString()).SetValue(tmp, myReader.GetString(index));      // to String
  82.                                                 break;
  83.                                             case "System.Boolean":
  84.                                                 typeof(T).GetProperty(row[0].ToString()).SetValue(tmp, myReader.GetBoolean(index));     // to Boolean
  85.                                                 break;
  86.                                             case "System.Decimal":
  87.                                                 typeof(T).GetProperty(row[0].ToString()).SetValue(tmp, myReader.GetDecimal(index));     // to Decimal
  88.                                                 break;
  89.                                                 // todo :: complete the convertion for oter types
  90.                                             default:
  91.                                                 break;
  92.                                         }
  93.                                     }
  94.                                 }
  95.                                 catch (Exception)
  96.                                 {
  97.                                     // todo :: should log any errors here
  98.                                 }
  99.                                 index++;   // increment the column indexer
  100.                             }
  101.                             ListOfT.Add(tmp);        // add the temp object (T) to the ListOfT
  102.                         }
  103.                     }
  104.                 }
  105.             }
  106.  
  107.             return ListOfT;
  108.         }
  109.  
  110.         public static T CreateInstanceOf_T<T>()
  111.         {
  112.             T tmp = (T)typeof(T).GetConstructor(new System.Type[] { }).Invoke(new object[] { });
  113.             return tmp;
  114.         }
  115.     }
  116. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement