88 lines
2.7 KiB
C#
88 lines
2.7 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Reflection;
|
|
using System.Threading.Tasks;
|
|
using MySql.Data.MySqlClient;
|
|
|
|
namespace Framework.Server {
|
|
public static class MySql {
|
|
|
|
private static MySqlConnection _connection;
|
|
|
|
public static void Initialize(string connectionString) {
|
|
_connection = new MySqlConnection(connectionString);
|
|
}
|
|
|
|
public static async Task Execute(string query) {
|
|
await _connection.OpenAsync();
|
|
var cmd = new MySqlCommand(query, _connection);
|
|
await cmd.ExecuteNonQueryAsync();
|
|
await _connection.CloseAsync();
|
|
}
|
|
|
|
public static async Task<List<T>> FetchAll<T>(string query) where T : new() {
|
|
await _connection.OpenAsync();
|
|
var cmd = new MySqlCommand(query, _connection);
|
|
var result = await cmd.ExecuteReaderAsync();
|
|
|
|
var data = new List<T>();
|
|
var columns = new Dictionary<string, int>();
|
|
var props = typeof(T).GetProperties();
|
|
|
|
for (int i = 0; i < result.FieldCount; i++)
|
|
columns.Add(result.GetName(i), i);
|
|
|
|
while (await result.ReadAsync()) {
|
|
var obj = new T();
|
|
|
|
for (int i = 0; i < result.FieldCount; i++) {
|
|
foreach (var property in props) {
|
|
if (columns.ContainsKey(property.Name)) {
|
|
property.SetValue(obj, ApplyValueConversion(result[columns[property.Name]], property));
|
|
}
|
|
}
|
|
}
|
|
|
|
data.Add(obj);
|
|
}
|
|
|
|
await _connection.CloseAsync();
|
|
|
|
return data;
|
|
}
|
|
|
|
public static async Task<T> FetchOne<T>(string query) where T : new() {
|
|
var result = await FetchAll<T>(query);
|
|
return result[0];
|
|
}
|
|
|
|
public static async void CreateTables(params string[] querys) {
|
|
var query = string.Join(";", querys);
|
|
await Execute(query);
|
|
}
|
|
|
|
private static object ApplyValueConversion(object value, PropertyInfo property) {
|
|
if (property.PropertyType == typeof(float[])) {
|
|
var raw = (value as string ?? "[0, 0, 0]")
|
|
.Replace("[", "")
|
|
.Replace("]", "")
|
|
.Replace(" ", "");
|
|
|
|
var values = raw
|
|
.Split(',')
|
|
.Select(Convert.ToSingle)
|
|
.ToArray();
|
|
|
|
return values;
|
|
}
|
|
|
|
if (property.PropertyType == typeof(uint)) {
|
|
return Convert.ToUInt32(value);
|
|
}
|
|
|
|
return value;
|
|
}
|
|
|
|
}
|
|
} |