Guest User

xTRUMANx

a guest
Feb 23rd, 2010
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 7.70 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Data.SQLite;
  6. using System.Data;
  7. using System.Reflection;
  8.  
  9. namespace hopeDBConsole
  10. {
  11.     public class DataLayer
  12.     {
  13.         private SQLiteConnection conn;
  14.         private SQLiteDataAdapter adapter;
  15.         private SQLiteCommand command;
  16.         private static DataSet set = new DataSet();
  17.  
  18.         // How do I test if connString is valid?
  19.         // i.e. Test if connection to db is working?
  20.         public DataLayer(string connString, params string[] tableNames)
  21.         {
  22.             conn = new SQLiteConnection();
  23.             conn.ConnectionString = connString;
  24.            
  25.             DataTable table = new DataTable();
  26.            
  27.             command = new SQLiteCommand();
  28.             command.Connection = conn;
  29.            
  30.             adapter = new SQLiteDataAdapter();
  31.  
  32.             #region Filling the DataSet with the tables in the Database
  33.             foreach (string tableName in tableNames)
  34.             {
  35.                 command.CommandText = "SELECT * FROM "+ tableName +";";  
  36.                 adapter.SelectCommand = command;
  37.                 adapter.Fill(set, tableName);
  38.                 table = set.Tables[tableName];
  39.                 SetPrimaryKey(table);
  40.             }
  41.             #endregion Finished filling the DataSet
  42.         }
  43.  
  44.         // All my tables have a column named id which is the PK.
  45.         public void SetPrimaryKey(DataTable table)
  46.         {
  47.             DataColumn[] key = new DataColumn[1];
  48.             DataColumn idCol = new DataColumn();
  49.             idCol = table.Columns["id"];
  50.             key[0] = idCol;
  51.             table.PrimaryKey = key;
  52.             idCol.AutoIncrement = true;
  53.         }
  54.  
  55.         public static DataTable GetTable(string tableName)
  56.         {
  57.             return set.Tables[tableName];
  58.         }
  59.  
  60.         public static DataTable GetTable(ISchoolObject thing)
  61.         {
  62.             string tableName = GetTableName(thing);
  63.             return GetTable(tableName);
  64.         }
  65.  
  66.         // My table names are lowercase versions of the class name.
  67.         // It would have been nice to have pluralization as in RoR.
  68.         public static string GetTableName(ISchoolObject thing)
  69.         {
  70.             return thing.GetType().ToString().ToLower();
  71.         }
  72.  
  73.         // TODO: Find out how Create could fail and make it return
  74.         // false to the caller.
  75.         public bool Create(ISchoolObject thing)
  76.         {
  77.             //string tableName = thing.GetType().ToString().ToLower(); // This string is used at end of this method
  78.             DataTable table = GetTable(thing);
  79.             string tableName = table.TableName;
  80.             // Get all the properties to be stored for the object
  81.             PropertyInfo[] properties = thing.GetType().GetProperties();
  82.  
  83.             #region Building InsertCommand
  84.             string columns = "";
  85.             string values = "";
  86.            
  87.             foreach (PropertyInfo property in properties)
  88.             {
  89.                 // Don't need the Id property when creating a *new* record
  90.                 if (property.Name != "Id")
  91.                 {
  92.                     string prop = property.Name.ToLower();
  93.                     columns += prop + ", ";
  94.                     values += "@" + prop + ", ";
  95.                     command.Parameters.Add("@" + prop, DbType.String, 0, prop);
  96.                 }
  97.             }
  98.             // Next two if statements remove the extra ", "
  99.             if(columns != "")
  100.                 columns = columns.Remove(columns.Length-2);
  101.             if(values != "")
  102.                 values = values.Remove(values.Length-2);
  103.             // Read up on your sql if the below makes no sense :-P
  104.             command.CommandText = "INSERT INTO " + tableName + "(" + columns + ") VALUES(" + values + ")";
  105.             adapter.InsertCommand = command;
  106.             #endregion InsertCommand is ready
  107.  
  108.             DataRow row = table.Rows.Add();
  109.             Save(thing, properties, row);
  110.            
  111.             int rowCount = table.Rows.Count;
  112.             long id = (long) table.Rows[rowCount - 1]["id"];
  113.             thing.Id = id;
  114.  
  115.             return true;
  116.         }
  117.  
  118.         // Excessive commenting below perhaps. May come in handy when
  119.         // I don't work with DataAdapters, DataSets and PropertyInfo
  120.         // objects for a while and read this method again.
  121.         public void Save(ISchoolObject thing, PropertyInfo[] properties, DataRow row)
  122.         {
  123.             foreach (PropertyInfo property in properties)
  124.             {
  125.                 // Assuming the property is called Age, this
  126.                 // statement is executed: row["age"] = thing.Age;
  127.                 if (property.Name != "Id")
  128.                     row[property.Name.ToLower()] = property.GetGetMethod().Invoke(thing, null);
  129.             }
  130.  
  131.             // This updates the local data set
  132.             adapter.Update(set, GetTableName(thing));
  133.  
  134.             // This actually saves changes to the
  135.             // dataset to the database
  136.             set.AcceptChanges();
  137.  
  138.             // Refilling the dataset so the generated
  139.             // id shows up in the dataset
  140.             RefillDataSet(GetTableName(thing));
  141.         }
  142.  
  143.         public void Update(ISchoolObject thing)
  144.         {
  145.             DataTable table = GetTable(thing);
  146.             string tableName = table.TableName;
  147.             PropertyInfo[] properties = thing.GetType().GetProperties();
  148.  
  149.             DataRow row = table.Rows.Find(thing.Id);
  150.  
  151.             CheckNullRow(row); // Throws an exception if row is null
  152.  
  153.             #region Building update commantText
  154.             // Can't get SQLiteCommandBuilder to work
  155.             command.CommandText = "UPDATE " + tableName + " SET ";
  156.             foreach (PropertyInfo property in properties)
  157.             {
  158.                 if (property.Name != "Id")
  159.                 {
  160.                     string prop = property.Name.ToLower();
  161.                     command.CommandText += prop + " = @" + prop + ", ";
  162.                     command.Parameters.Add("@" + prop, DbType.String, 0, prop);
  163.                 }
  164.             }
  165.             command.CommandText = command.CommandText.Remove(command.CommandText.Length - 2);
  166.             command.CommandText += " WHERE id = @id";
  167.             command.Parameters.Add("@id", DbType.Int64, 0, "id");
  168.             adapter.UpdateCommand = command;
  169.             #endregion Update command ready
  170.  
  171.             Save(thing, properties, row);
  172.         }
  173.  
  174.         public void Delete(ISchoolObject thing)
  175.         {
  176.             DataTable table = GetTable(thing);
  177.  
  178.             DataRow row = table.Rows.Find(thing.Id);
  179.             CheckNullRow(row); // Throws an exception if row is null
  180.  
  181.             row.Delete();
  182.            
  183.             command.CommandText = "DELETE FROM " + table.TableName + " WHERE id = " + thing.Id;
  184.             adapter.DeleteCommand = command;
  185.  
  186.             adapter.Update(set, table.TableName);
  187.             set.AcceptChanges();
  188.            
  189.             // Refilling dataset so that deleted entry
  190.             // is removed from the dataset
  191.             RefillDataSet(table.TableName);
  192.         }
  193.  
  194.         // Built this method since I don't know of a command
  195.         // that accomplishes the same task
  196.         public void RefillDataSet(string tableName)
  197.         {
  198.             adapter.SelectCommand.CommandText = "SELECT * FROM " + tableName;
  199.             set.Tables[tableName].Clear();
  200.             adapter.Fill(set, tableName);
  201.         }
  202.  
  203.         public void CheckNullRow(DataRow row)
  204.         {
  205.             if (row == null)
  206.                 throw new RowNotInTableException("The row you are updating/deleting is not in the DataTable.");
  207.         }
  208.     }
  209. }
  210.  
Advertisement
Add Comment
Please, Sign In to add comment