From 38876d441e19b2164749930a4a0aa5bcf3ab492f Mon Sep 17 00:00:00 2001 From: Daniel-I-Am Date: Thu, 4 Jun 2020 01:54:27 +0200 Subject: [PATCH] Add DB controller search method --- ChaosBot/Database/Controller.cs | 55 +++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/ChaosBot/Database/Controller.cs b/ChaosBot/Database/Controller.cs index a5f0217..43ad76a 100644 --- a/ChaosBot/Database/Controller.cs +++ b/ChaosBot/Database/Controller.cs @@ -1,9 +1,11 @@ using System; using System.Collections.Generic; using System.Data; +using System.Linq; using System.Text; using Microsoft.Data.Sqlite; using Microsoft.Extensions.Configuration; +using Microsoft.VisualBasic; using NLog; namespace ChaosBot.Database @@ -88,5 +90,58 @@ namespace ChaosBot.Database _logger.Fatal($"Controllers.DBWork.RawQuery: Exception [{ex}] thrown, <[{ex.Message}]>."); } } + + public static DataTable SelectQuery(string table, string selectColumns = "*", Dictionary filterColumns = null, string orderByKey = null) + { + DataTable dt = new DataTable(); + + try + { + using (_conn) + { + _conn.Open(); + SqliteCommand cmd = _conn.CreateCommand(); + + string filter = null; + if (filterColumns != null) + { + List filterList = new List(); + foreach (string key in filterColumns.Keys) + { + filterList.Add($"{key} = @{key}"); + } + + filter = $"WHERE {Strings.Join(filterList.ToArray(), " AND ")}"; + + foreach (string key in filterColumns.Keys) + { + cmd.Parameters.AddWithValue($@"{key}", filterColumns.GetValueOrDefault(key)); + } + } + + string order = null; + if (orderByKey != null) + { + order = $"ORDER BY ${orderByKey}"; + } + + string query = $"SELECT {selectColumns} FROM {table} {filter} {order}"; + + cmd.CommandText = query; + cmd.Prepare(); + SqliteDataReader executeReader = cmd.ExecuteReader(); + + dt.Load(executeReader); + + _conn.Close(); + } + } + catch (Exception ex) + { + _logger.Fatal($"Controllers.DBWork.RawQuery: Exception [{ex}] thrown, <[{ex.Message}]>."); + } + + return dt; + } } } \ No newline at end of file