using System;
using System.Collections.Generic;
using System.Data;
using DX86.Modules;
using MySql.Data.MySqlClient;
using Newtonsoft.Json;
namespace Server
{
public class MySQL
{
private MySqlConnection _connection;
private MessageSender ms;
public MySQL(string username, string password, string server, string port, string database, MessageSender ms)
{
this.ms = ms;
ms.Log("[MySQL] Initializing connection...");
// include port in the connection string:
string connectionString = $"Server={server};Port={port};Database={database};User ID={username};Password={password};";
_connection = new MySqlConnection(connectionString);
ms.Log("[MySQL] Connection to database...");
try
{
_connection.Open();
ms.Log("[MySQL] Connection established.");
}
catch (Exception ex)
{
ms.Error("[MySQL] Connection failed: " + ex.Message);
ms.Error("[MySQL] Please check your connection settings.");
ms.Error("[MySQL] Make sure the MySQL server is running and accessible.");
ms.Error("[MySQL] A MySQL Connection is necessary to run this application.");
ms.Error("[MySQL] Exiting...");
Environment.Exit(1);
}
}
private string JsonResponse(object data, bool error = false)
{
return JsonConvert.SerializeObject(new { error, data });
}
private string GetType(object value)
{
return value switch
{
int => "i",
float or double => "d",
string => "s",
_ => "b"
};
}
///
/// Executes a non‐query SQL statement (e.g. CREATE TABLE, ALTER, etc.).
/// Returns null on success, or an error JSON if it fails.
///
public string ExecuteNonQuery(string sql)
{
using var cmd = new MySqlCommand(sql, _connection);
try
{
cmd.ExecuteNonQuery();
return JsonResponse(new { success = true });
}
catch (Exception ex)
{
return JsonResponse($"Execute failed: {ex.Message}", true);
}
}
public string Insert(string table, Dictionary data)
{
string columns = string.Join(", ", data.Keys);
string placeholders = string.Join(", ", new string[data.Count].Select(_ => "?"));
string sql = $"INSERT INTO `{table}` ({columns}) VALUES ({placeholders})";
using var cmd = new MySqlCommand(sql, _connection);
string types = "";
foreach (var value in data.Values)
{
types += GetType(value);
cmd.Parameters.AddWithValue(null, value);
}
try
{
cmd.ExecuteNonQuery();
long insertId = cmd.LastInsertedId;
return JsonResponse(new { insert_id = insertId });
}
catch (Exception ex)
{
return JsonResponse($"Execute failed: {ex.Message}", true);
}
}
public string Get(string table, Dictionary parameters = null, int? limit = null, int? offset = null)
{
string sql = $"SELECT * FROM `{table}`";
string types = "";
var values = new List