Last active
          August 29, 2015 14:01 
        
      - 
      
- 
        Save hagbarddenstore/0e957e85b09610fe1a5a to your computer and use it in GitHub Desktop. 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | public abstract class Database | |
| { | |
| public Database(string connectionString) | |
| { | |
| ConnectionString = connectionString; | |
| } | |
| protected string ConnectionString { get; private set; } | |
| public IEnumerable<IDictionary<string, object>> Query(string query, object parameters = null) | |
| { | |
| var rows = new List<IDictionary<string, object>>(); | |
| using (var connection = CreateConnection()) | |
| using (var command = connection.CreateCommand()) | |
| { | |
| command.CommandText = query; | |
| if (parameters != null) | |
| { | |
| foreach (var parameter in ToDictionary(parameters)) | |
| { | |
| var p = command.CreateParameter(); | |
| p.ParameterName = parameter.Key; | |
| p.Value = parameter.Value; | |
| command.Parameters.Add(p); | |
| } | |
| } | |
| connection.Open(); | |
| using (var reader = command.ExecuteReader()) | |
| { | |
| while (reader.Read()) | |
| { | |
| var values = new Dictionary<string, object>(); | |
| for (var fieldIndex = 0; fieldIndex < reader.FieldCount; fieldIndex++) | |
| { | |
| values.Add(reader.GetName(fieldIndex), reader.GetValue(fieldIndex)); | |
| } | |
| rows.Add(values); | |
| } | |
| } | |
| connection.Close(); | |
| } | |
| return rows; | |
| } | |
| protected abstract IDbConnection CreateConnection(); | |
| protected IDictionary<string, object> ToDictionary(object source) | |
| { | |
| var dictionary = new Dictionary<string, object>(); | |
| foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(source)) | |
| { | |
| var value = property.GetValue(source); | |
| dictionary.Add(property.Name, value); | |
| } | |
| return dictionary; | |
| } | |
| } | |
| public class MySqlDatabase : Database | |
| { | |
| public MySqlDatabase(string connectionString) | |
| : base(connectionString) | |
| { | |
| } | |
| protected override IDbConnection CreateConnection() | |
| { | |
| return new MySqlConnection(ConnectionString); | |
| } | |
| } | |
| public class NpgsqlDatabase : Database | |
| { | |
| public NpgsqlDatabase(string connectionString) | |
| : base(connectionString) | |
| { | |
| } | |
| protected override IDbConnection CreateConnection() | |
| { | |
| return new NpgsqlConnection(ConnectionString); | |
| } | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment