92 lines
3.0 KiB
C#
92 lines
3.0 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Data;
|
|
using System.Text;
|
|
using Microsoft.Data.Sqlite;
|
|
using Microsoft.Extensions.Configuration;
|
|
using NLog;
|
|
|
|
namespace ChaosBot.Database
|
|
{
|
|
public static class Controller
|
|
{
|
|
static SqliteConnection _conn = new SqliteConnection($"Data Source={System.IO.Directory.GetCurrentDirectory()}/{Program.Cfg.GetValue<string>("Bot:Database")}");
|
|
private static Logger _logger = Program._logger;
|
|
|
|
public static DataTable RawQuery(string query)
|
|
{
|
|
DataTable dt = new DataTable();
|
|
|
|
try
|
|
{
|
|
using (_conn)
|
|
{
|
|
_conn.Open();
|
|
|
|
SqliteCommand cmd = _conn.CreateCommand();
|
|
cmd.CommandText = query;
|
|
SqliteDataReader executeReader = cmd.ExecuteReader(CommandBehavior.SingleResult);
|
|
|
|
dt.Load(executeReader);
|
|
|
|
_conn.Close();
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.Fatal($"Controllers.DBWork.RawQuery: Exception [{ex}] thrown, <[{ex.Message}]>.");
|
|
}
|
|
|
|
return dt;
|
|
}
|
|
|
|
public static void InsertQuery(string table, Dictionary<string, object> parameters)
|
|
{
|
|
try
|
|
{
|
|
using (_conn)
|
|
{
|
|
_conn.Open();
|
|
|
|
SqliteCommand cmd = _conn.CreateCommand();
|
|
StringBuilder commandText = new StringBuilder();
|
|
commandText.Append("INSERT INTO ");
|
|
commandText.Append(table);
|
|
commandText.Append(" (");
|
|
|
|
foreach (string key in parameters.Keys)
|
|
{
|
|
commandText.Append($"{key}, ");
|
|
}
|
|
|
|
commandText.Remove(commandText.Length - 2, 2);
|
|
commandText.Append(") VALUES (");
|
|
|
|
foreach (string key in parameters.Keys)
|
|
{
|
|
commandText.Append($"@{key},");
|
|
}
|
|
|
|
commandText.Remove(commandText.Length - 1, 1);
|
|
commandText.Append(")");
|
|
|
|
cmd.CommandText = commandText.ToString();
|
|
|
|
foreach (string key in parameters.Keys)
|
|
{
|
|
cmd.Parameters.AddWithValue($"@{key}", parameters.GetValueOrDefault(key));
|
|
}
|
|
|
|
cmd.Prepare();
|
|
cmd.ExecuteNonQuery();
|
|
|
|
_conn.Close();
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.Fatal($"Controllers.DBWork.RawQuery: Exception [{ex}] thrown, <[{ex.Message}]>.");
|
|
}
|
|
}
|
|
}
|
|
} |