Files
PWAPP/PWAPPv2/Source/Database/DatabaseConnection.cs
Matthew Burke 1b65e9bb83 Lots of updates
2023-07-26 22:26:54 -04:00

116 lines
2.9 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Data.SqlClient;
using MySqlConnector;
namespace PWAPPv2.Source.Database
{
class DatabaseConnection
{
private MySqlConnection Connection;
private string SqlString;
DatabaseConfig Config;
public DatabaseConnection(DatabaseConfig config)
{
Config = config;
SqlString = "server=" + config.host + ";Uid=" + config.user + ";database=" + config.database + ";Pwd=" + config.password;
Connection = new MySqlConnection(SqlString);
}
public void Connect()
{
try
{
Connection.Open();
}
catch(Exception)
{
throw new DatabaseConnectionException();
}
}
public List<string> QueryDatabase(string query)
{
try
{
Connection.Open();
}
catch (Exception)
{
throw new CouldNotOpenConnectionException();
}
MySqlCommand Command = new MySqlCommand(query, Connection);
MySqlDataReader reader;
try
{
reader = Command.ExecuteReader();
}
catch (Exception)
{
Connection.Close();
throw new ReaderException();
}
List<string> result = new List<string>();
while (reader.Read())
{
int n = reader.VisibleFieldCount;
for (int i = 0; i < reader.VisibleFieldCount; i++)
{
var type = reader.GetFieldType(i);
if (type.Name == "Int64")
{
result.Add(reader.GetInt64(i).ToString());
}
if (type.Name == "Int32")
{
result.Add(reader.GetInt32(i).ToString());
}
if (type.Name == "String")
{
result.Add(reader.GetString(i));
}
if (type.Name == "Byte")
{
result.Add(reader.GetByte(i).ToString());
}
if (type.Name == "DateTime")
{
result.Add(reader.GetDateTime(i).ToString());
}
}
}
Connection.Close();
return result;
}
}
class DatabaseConfigurationException : Exception
{
}
class DatabaseConnectionException : Exception
{ }
class CouldNotOpenConnectionException : Exception
{
}
class ReaderException : Exception
{
}
}