it's working using parameters, so there is no chance of MySql injection (or at least decreased it), but it could be a bit slower.
i'm sorry if this is a totally wrong way of do it, it could be because my inexperience at C# and MySql syntax(this is the first time that i really try learn about MySql).
Also the update methods(Update, Insert and Delete) are being executed by a thread to get the less possible delay when doing one of these types of consults(a thread and a queue, it can have more than 1 thread working, but can cause some bugs when inserting and updating the same row with no pause.
again, srry if this is a bad way of do it, i pm'ed cptsky if he could do a fast check to the code to evade any possible flaming, but looks like he is almost all the time disconnected, so hope i can get constructive criticism
Old
DBCore.cs //Connection info, create MySql connection method
DBEnums.cs //enums for type of consult and connection protocol(tcp or named pipe)
DBThread.cs //contains the thread that will create the MySqlCommands, add the text created in the custom MySQLCommands, add the parameters, and execute them.
MySQLCommand//Nothing special, some replace methods, a dictionary for the parameters and a Tuple for the where statment
MySQLReader.cs //obvious(?)
ThreadFactory.cs//Wrapper for the Thread class
Code:
/*****************************************************************************
* Author: Caparzo/U2_Caparzo.
* Code written for the project MyConquer_Core.
*
* Date: 09/05/2013
* Hour: 2:08
*
* Feel free to use or redistribute this class with any project, but please
* keep this header so credits still goes to the coder of the class.
*****************************************************************************/
using System.Text;
using MySql.Data.MySqlClient;
namespace MyConquer_Core.MySQL
{
/// <summary>
/// Description of DBCore.
/// </summary>
public class DBCore
{
#region private/protected members
private static string connectionString = string.Empty;
#endregion
#region internal/public members
/// <summary>
/// MySQL username, default = root
/// </summary>
public static string DB_Username = "root";
/// <summary>
/// MySQL Password
/// </summary>
public static string DB_Password;
/// <summary>
/// Database name
/// </summary>
public static string DB_Name;
/// <summary>
/// Connection protocol, default = Tcp socket
/// </summary>
public static MySQLProtocol Protocol = MySQLProtocol.Tcp;
/// <summary>
/// Used only if th Protocol is Tcp, this sets the name for the pipe, defaul = the database name
/// </summary>
public static string PipeName = string.Empty;
/// <summary>
/// Define if the connection should use the MySQL Pooling, default = true
/// </summary>
public static bool UsePooling = true;
/// <summary>
/// Used only if UsePooling is true, define the maximum size of the MySQL pool, dafault = 50
/// </summary>
public static int MaxPoolSize = 50;
#endregion
#region methods
/// <summary>
/// Gets a new opened MySqlConnection
/// </summary>
/// <returns></returns>
public static MySqlConnection GetNewConnection()
{
if (connectionString == string.Empty)
CreateConnectionString();
MySqlConnection conn = new MySqlConnection(connectionString);
conn.Open();
return conn;
}
private static void CreateConnectionString()
{
StringBuilder connString = new StringBuilder();
connString.Append("Server=127.0.0.1;");
connString.Append("Database=" + DB_Name + ';');
connString.Append("Uid=" + DB_Username + ';');
connString.Append("Pwd=" + DB_Password + ';');
if (Protocol == MySQLProtocol.Pipe)
{
if (PipeName == string.Empty)
PipeName = DB_Name;
connString.Append("Protocol=pipe;PipeName=" + DB_Name + ';');
}
if (UsePooling)
{
connString.Append("Pooling=True;maximumpoolsize=" + MaxPoolSize.ToString() + ';');
}
connString.Append("ConnectionLifeTime=60;");
connectionString = connString.ToString();
}
#endregion
}
}
DBEnums.cs //enums for type of consult and connection protocol(tcp or named pipe)
Code:
/*****************************************************************************
* Author: Caparzo/U2_Caparzo.
* Code written for the project MyConquer_Core.
*
* Date: 09/05/2013
* Hour: 2:40
*
* Feel free to use or redistribute this class with any project, but please
* keep this header so credits still goes to the coder of the class.
*****************************************************************************/
using System;
namespace MyConquer_Core.MySQL
{
public enum CommandType
{
INSERT,
UPDATE,
DELETE
}
public enum MySQLProtocol
{
Tcp,
Pipe
}
}
DBThread.cs //contains the thread that will create the MySqlCommands, add the text created in the custom MySQLCommands, add the parameters, and execute them.
Code:
/*****************************************************************************
* Author: Caparzo/U2_Caparzo.
* Code written for the project MyConquer_Core.
*
* Date: 09/05/2013
* Hour: 2:27
*
* Feel free to use or redistribute this class with any project, but please
* keep this header so credits still goes to the coder of the class.
*****************************************************************************/
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;
using MySql.Data.MySqlClient;
namespace MyConquer_Core.MySQL
{
/// <summary>
/// Thread that will execute all the update/insert MySql commands
/// </summary>
public class DBThread
{
#region private/protected members
private static int _AmountOfWorkers = 1;
/// <summary>
/// Sets the amount of threads working, set this before start the database
/// </summary>
private static ThreadFactory workers;
private static ConcurrentQueue<MySQLCommand> commands = new ConcurrentQueue<MySQLCommand>();
#endregion
#region properties
public static int AmountOfWorkers
{
get{return _AmountOfWorkers;}
set{_AmountOfWorkers = value;}
}
#endregion
#region methods
private static void ExecuteCommands()
{
MySQLCommand cmd;
if(commands.TryDequeue(out cmd))
{
using(var conn = DBCore.GetNewConnection())
{
using(MySqlCommand command = new MySqlCommand())
{
command.Connection = conn;
switch(cmd.type)
{
#region insert
case CommandType.INSERT:
{
StringBuilder tempFields = new StringBuilder();
StringBuilder tempValues = new StringBuilder();
bool started = false;
foreach(KeyValuePair<string, object> pair in cmd.InsertValues)
{
if(!started)
{
tempFields.Append(pair.Key);
tempValues.Append('?' + pair.Key);
started = true;
}
else
{
tempFields.Append("," + pair.Key);
tempValues.Append(",?" + pair.Key);
}
command.Parameters.AddWithValue('?' + pair.Key, pair.Value);
}
cmd.command.Replace("<F>", tempFields.ToString());
cmd.command.Replace("<V>", tempValues.ToString());
command.CommandText = cmd.GetCommand();
command.ExecuteNonQuery();
break;
}
#endregion
#region update
case CommandType.UPDATE:
{
bool started = false;
foreach(KeyValuePair<string, object> pair in cmd.InsertValues)
{
if(!started)
{
cmd.command.Append(" Set " + pair.Key+"=?" + pair.Key + ' ');
started = true;
}
else
{
cmd.command.Append(',' + pair.Key+"=?" + pair.Key + ' ');
}
command.Parameters.AddWithValue('?' + pair.Key, pair.Value);
}
if(cmd.WhereStatment != null)
{
cmd.command.Append("where " + cmd.WhereStatment.Item1 + "=?1" + cmd.WhereStatment.Item1);
command.Parameters.AddWithValue("?1" + cmd.WhereStatment.Item1, cmd.WhereStatment.Item2);
}
command.CommandText = cmd.GetCommand();
command.ExecuteNonQuery();
break;
}
#endregion
#region delete
case CommandType.DELETE:
{
// = cmd.GetCommand();
cmd.command.Replace("<F>", cmd.WhereStatment.Item1);
cmd.command.Replace("<V>", '?' + cmd.WhereStatment.Item1);
command.Parameters.AddWithValue('?'+ cmd.WhereStatment.Item1, cmd.WhereStatment.Item2);
command.CommandText = cmd.GetCommand();
command.ExecuteNonQuery();
break;
}
#endregion
}
}
}
}
}
public static void Start()
{
workers = new ThreadFactory(2, AmountOfWorkers);
workers.invokers += ExecuteCommands;
workers.Start();
}
public static void Enqueue(MySQLCommand cmd)
{
commands.Enqueue(cmd);
}
#endregion
}
}
MySQLCommand//Nothing special, some replace methods, a dictionary for the parameters and a Tuple for the where statment
Code:
/*****************************************************************************
* Author: Caparzo/U2_Caparzo.
* Code written for the project MyConquer_Core.
*
* Date: 09/05/2013
* Hour: 2:34
*
* Feel free to use or redistribute this class with any project, but please
* keep this header so credits still goes to the coder of the class.
*****************************************************************************/
using System;
using System.Text;
namespace MyConquer_Core.MySQL
{
/// <summary>
/// Wrapper for the MySqlCommand.
/// </summary>
public class MySQLCommand
{
#region internal/public members
internal StringBuilder command;
internal Dictionary<string, object> InsertValues;
internal Tuple<string, object> WhereStatment;
public CommandType type;
#endregion
#region constructors
public MySQLCommand(CommandType Type)
{
this.type = Type;
WhereStatment = null;
InsertValues = new Dictionary<string, object>();
command = new StringBuilder();
switch(type)
{
case CommandType.INSERT:
{
command.Append("INSERT INTO <T> (<F>) VALUES (<V>)");
break;
}
case CommandType.UPDATE:
{
command.Append("UPDATE <T>");
break;
}
case CommandType.DELETE:
{
command.Append("DELETE FROM <T> where <F> = <V>");
break;
}
}
}
#endregion
#region methods
public MySQLCommand Insert(string Table)
{
command.Replace("<T>", Table);
return this;
}
public MySQLCommand Insert(string field, object value)
{
InsertValues.Add(field, value);
return this;
}
public MySQLCommand Update(string Table)
{
command.Replace("<T>", Table);
return this;
}
public MySQLCommand Set(string field, object value)
{
InsertValues.Add(field, value);
return this;
}
public void Execute()
{
DBThread.Enqueue(this);
}
public MySQLCommand Where(string field, object value)
{
WhereStatment = new Tuple<string, object>(field, value);
return this;
}
public MySQLCommand Limit(int limit)
{
command.Append("LIMIT "+ limit.ToString() + ';');
return this;
}
public MySQLCommand Delete(string Table)
{
command.Replace("<T>", Table);
return this;
}
public MySQLCommand Delete(string field, object value)
{
WhereStatment = new Tuple<string, object>(field, value);
return this;
}
public string GetCommand()
{
return command.ToString();
}
#endregion
}
}
MySQLReader.cs //obvious(?)
Code:
/*****************************************************************************
* Author: Caparzo/U2_Caparzo.
* Code written for the project MyConquer_Core.
*
* Date: 09/05/2013
* Hour: 2:38
*
* Feel free to use or redistribute this class with any project, but please
* keep this header so credits still goes to the coder of the class.
*****************************************************************************/
using System;
using System.Text;
using MySql.Data.MySqlClient;
namespace MyConquer_Core.MySQL
{
/// <summary>
/// Wrapper for the MySqlDataReader class.
/// </summary>
public class MySQLReader
{
#region private/protected members
private StringBuilder command;
private MySqlDataReader reader;
private MySqlCommand cmd;
#endregion
#region constructors
public MySQLReader()
{
command = new StringBuilder("SELECT * FROM <T>");
cmd = DBCore.GetNewConnection().CreateCommand();
}
#endregion
#region methods
/// <summary>
/// Select the table that contains the data that will be read
/// </summary>
/// <param name="Table">Table name</param>
/// <returns></returns>
public MySQLReader Select(string Table)
{
command.Replace("<T>", Table);
return this;
}
/// <summary>
/// Select the column that contains the needed data
/// </summary>
/// <param name="Column">Column name</param>
/// <returns></returns>
public MySQLReader SelectColumn(string Column)
{
command.Replace("*", Column);
return this;
}
public MySQLReader Where(string Column, object value)
{
command.Append(" where " + Column + "=?" + Column);
cmd.Parameters.AddWithValue('?' + Column, value);
return this;
}
public void Execute()
{
cmd.CommandText = command.ToString();
reader = cmd.ExecuteReader();
}
public MySQLReader ReadSByte(string Column, out sbyte value)
{
value = default(sbyte);
if(reader.Read())
value = reader.GetSByte(Column);
return this;
}
public MySQLReader ReadByte(string Column, out byte value)
{
value = default(byte);
if(reader.Read())
value = reader.GetByte(Column);
return this;
}
public MySQLReader ReadInt16(string Column, out Int16 value)
{
value = default(short);
if(reader.Read())
value = reader.GetInt16(Column);
return this;
}
public MySQLReader ReadUInt16(string Column, out UInt16 value)
{
value = default(ushort);
if(reader.Read())
value = reader.GetUInt16(Column);
return this;
}
public MySQLReader ReadInt32(string Column, out Int32 value)
{
value = default(int);
if(reader.Read())
value = reader.GetInt32(Column);
return this;
}
public MySQLReader ReadUInt32(string Column, out UInt32 value)
{
value = default(uint);
if(reader.Read())
value = reader.GetUInt32(Column);
return this;
}
public MySQLReader ReadInt64(string Column, out Int64 value)
{
value = default(long);
if(reader.Read())
value = reader.GetInt64(Column);
return this;
}
public MySQLReader ReadUInt64(string Column, out UInt64 value)
{
value = default(ulong);
if(reader.Read())
value = reader.GetUInt64(Column);
return this;
}
public MySQLReader ReadString(string Column, out string value)
{
value = default(string);
if(reader.Read())
value = reader.GetString(Column);
return this;
}
public MySQLReader ReadBool(string Column, out bool value)
{
value = default(bool);
if(reader.Read())
value = reader.GetBoolean(Column);
return this;
}
public MySQLReader ReadDateTime(string Column, out DateTime value)
{
value = default(DateTime);
if(reader.Read())
value = reader.GetDateTime(Column);
return this;
}
/// <summary>
/// Free the resources used by the MySQLReader
/// </summary>
public void Dispose()
{
cmd.Dispose();
cmd.Connection.Dispose();
reader.Dispose();
}
#endregion
}
}
Code:
/*****************************************************************************
* Author: Caparzo/U2_Caparzo.
* Code written for the project MyConquer_Core.
*
* Date: 09/05/2013
* Hour: 1:55
*
* Feel free to use or redistribute this class with any project, but please
* keep this header so credits still goes to the coder of the class.
*****************************************************************************/
using System;
using System.Threading;
namespace MyConquer_Core
{
/// <summary>
/// Wrapper for the Thread class.
/// </summary>
public class ThreadFactory
{
#region private/protected members
private Thread[] workers;
private int sleepTime;
#endregion
#region internal/public members
/// <summary>
/// Methods that will be invoked by the worker
/// </summary>
public event Action invokers;
#endregion
#region constructors
/// <summary>
/// Create a new Worker, with a defined sleep time and amount of threads workers
/// </summary>
/// <param name="loopTime">Time that the threads will wait untill the next execute occurs</param>
/// <param name="amount">Amount of threds that will execute the methods</param>
public ThreadFactory(int loopTime, int amount)
{
sleepTime = loopTime;
workers = new Thread[amount];
for(int i = 0; i < amount; i++)
{
workers[i] = new Thread(execute);
}
}
#endregion
#region methods
/// <summary>
/// Start the threads
/// </summary>
public void Start()
{
for(int i = 0; i < workers.Length; i++)
{
workers[i].Start();
}
}
private void execute()
{
try
{
while(true)
{
invokers.Invoke();
Thread.Sleep(sleepTime);
}
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
}
#endregion
}
}
First revision
Removed DBThread, renamed some variables, renamed classes, edited the code to prevent errors(maybe this was not done in a good way, u could have used pre-processors but since this was intendeed to be a dll, i didn't )
Added support to execute asynchronously using BeginExecute() instead using the DBThread in the old version, of course it can be executed sinchronously with the Execute method.
Added support for multiple where statments.
The MySqlReader still the same, i guess i will edit it in some days since i got a lot to study, and i have 0 knowledge about DataAdapater, DataSet an DataRow :/
MySqlCore//Old DBCore, now using MySqlConnectionStringBuilder and some checks to the string values
MySqlWriter//Old MySqlCommand, now it wraps the MySqlCommand, and as stated before, support multiple where statmens for the Update methods, plus some checks for possible wrong commands
MySqlEnums//same than before, a few enums added
MySqlReader//Same than before for the moment :/
Added support to execute asynchronously using BeginExecute() instead using the DBThread in the old version, of course it can be executed sinchronously with the Execute method.
Added support for multiple where statments.
The MySqlReader still the same, i guess i will edit it in some days since i got a lot to study, and i have 0 knowledge about DataAdapater, DataSet an DataRow :/
MySqlCore//Old DBCore, now using MySqlConnectionStringBuilder and some checks to the string values
Code:
/*****************************************************************************
* Author: Caparzo/U2_Caparzo.
* Code written for the project MySqlWrapper.
*
* Date: 10/05/2013
* Hour: 1:20
*
* Feel free to use or redistribute this class with any project, but please
* keep this header so credits still goes to the coder of the class.
*****************************************************************************/
using System;
using MySql.Data.MySqlClient;
namespace MySqlWrapper
{
/// <summary>
/// Core for the MySqlWrapper, contains the configuration and
/// methods to get a new MySql connection.
/// </summary>
public class MySqlCore
{
private static string connectionString;
public static string UserID = "root";
public static string Password;
public static string Database;
public static MySqlProtocol Protocol = MySqlProtocol.Tcp;
public static string PipeName = "MyDBPipe";
public static bool UsePooling = false;
public static uint MaxPoolSize = 50;
public static uint MinPoolSize = 0;
public static bool ThrowExceptions = false;
public static MySqlConnection GetNewConnection()
{
if (string.IsNullOrEmpty(connectionString))
CreateConnectionString();
MySqlConnection conn = new MySqlConnection(connectionString);
conn.Open();
return conn;
}
public static void CreateConnectionString()
{
#region sanity checks
if (string.IsNullOrEmpty(Password))
throw new NullReferenceException("The password to connect to MySql can not be null or empty");
else if (string.IsNullOrEmpty(Database))
throw new NullReferenceException("The Database name can not be null or empty");
else if (Protocol != MySqlProtocol.Tcp && Protocol != MySqlProtocol.NamedPipe)
throw new NullReferenceException("The connection Protocol must be Tcp or NamedPipe");
else if (Protocol == MySqlProtocol.NamedPipe && string.IsNullOrEmpty(PipeName))
throw new NullReferenceException("the name for the NamedPipe can not be null or empty");
#endregion
MySqlConnectionStringBuilder connStringBuilder = new MySqlConnectionStringBuilder();
connStringBuilder.UserID = !string.IsNullOrEmpty(UserID) ? UserID : "root";
connStringBuilder.Password = Password;
connStringBuilder.Database = Database;
if (Protocol == MySqlProtocol.NamedPipe)
connStringBuilder.PipeName = PipeName;
if (UsePooling)
{
connStringBuilder.Pooling = true;
connStringBuilder.MaximumPoolSize = MaxPoolSize;
connStringBuilder.MinimumPoolSize = MinPoolSize;
}
connectionString = connStringBuilder.ToString();
}
}
}
MySqlWriter//Old MySqlCommand, now it wraps the MySqlCommand, and as stated before, support multiple where statmens for the Update methods, plus some checks for possible wrong commands
Code:
/*****************************************************************************
* Author: Caparzo/U2_Caparzo.
* Code written for the project MySqlWrapper.
*
* Date: 10/05/2013
* Hour: 1:19
*
* Feel free to use or redistribute this class with any project, but please
* keep this header so credits still goes to the coder of the class.
*****************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using MySql.Data.MySqlClient;
namespace MySqlWrapper
{
struct MySqlWhere
{
public string Field;
public object Value;
public MySqlWhereConnector Connector;
public MySqlWhereType Type;
}
/// <summary>
/// Wrapper for the MySqlCommand from the .net connector to MySql.
/// </summary>
public class MySqlWriter
{
private Dictionary<string, object> insertValues;
private Dictionary<string, MySqlWhere> whereStatments;
private StringBuilder command;
private MySqlCommandType commandType;
private MySqlWhereConnector nextConnector;//To implement 'And' and 'Or'
public MySqlWriter(MySqlCommandType type)
{
this.commandType = type;
this.whereStatments = new Dictionary<string,MySqlWhere>();
this.insertValues = new Dictionary<string, object>();
this.command = new StringBuilder();
switch (type)
{
case MySqlCommandType.Insert:
{
this.command.Append("Insert Into <T> (<F>) Values (<V>)");
break;
}
case MySqlCommandType.Update:
{
this.command.Append("Update <T>");
break;
}
case MySqlCommandType.Delete:
{
this.command.Append("Delete From <T> Where <F> = <V>");
break;
}
default:
{
throw new Exception("The type of MySqlCommand must be Insert, Update or Delete!");
}
}
}
public bool SelectTable(string table)
{
if (this.command.ToString().Contains("<T>"))
{
this.command.Replace("<T>", table);
return true;
}
else
{
if (MySqlCore.ThrowExceptions)
throw AlreadyChosenTableException();
else
return false;
}
}
public bool Insert(string field, object value)
{
if (this.commandType != MySqlCommandType.Insert)
{
if (MySqlCore.ThrowExceptions)
throw WrongTypeException("Insert", "Insert");
else
return false;
}
else
{
if (this.insertValues.ContainsKey(field))
{
if (MySqlCore.ThrowExceptions)
throw AlreadyUsedFieldException(field);
else
return false;
}
else
{
this.insertValues.Add(field, value);
return true;
}
}
}
public bool Update(string field, object value)
{
if (this.commandType != MySqlCommandType.Update)
{
if (MySqlCore.ThrowExceptions)
throw WrongTypeException("Update", "Update");
else
return false;
}
else
{
if (this.insertValues.ContainsKey(field))
{
if (MySqlCore.ThrowExceptions)
throw AlreadyUsedFieldException(field);
else
return false;
}
else
{
this.insertValues.Add(field, value);
return true;
}
}
}
public bool Delete(string field, object value)
{
if (this.commandType != MySqlCommandType.Delete)
{
if (MySqlCore.ThrowExceptions)
throw WrongTypeException("Delete", "Delete");
else
return false;
}
else if (this.insertValues.Count > 0)
{
throw new Exception("Only one delete statment is allowed by the MySqlWriter");
}
else
{
if (this.insertValues.ContainsKey(field))
{
if (MySqlCore.ThrowExceptions)
throw AlreadyUsedFieldException(field);
else
return false;
}
else
{
this.insertValues.Add(field, value);
return true;
}
}
}
public bool WhereMatch(string field, object value)
{
if (this.commandType != MySqlCommandType.Update)
{
if (MySqlCore.ThrowExceptions)
throw WrongTypeException("WhereMatch", "Update");
else
return false;
}
else if (this.whereStatments.ContainsKey(field))
{
if (MySqlCore.ThrowExceptions)
throw AlreadyUsedFieldException(field);
else
return false;
}
else
{
MySqlWhere whereStatment = new MySqlWhere();
whereStatment.Field = field;
whereStatment.Connector = nextConnector;
whereStatment.Type = MySqlWhereType.Equal;
whereStatment.Value = value;
this.whereStatments.Add(field, whereStatment);
return true;
}
}
public bool WhereDistinct(string field, object value)
{
if (this.commandType != MySqlCommandType.Update)
{
if (MySqlCore.ThrowExceptions)
throw WrongTypeException("WhereMatch", "Update");
else
return false;
}
else if (this.whereStatments.ContainsKey(field))
{
if (MySqlCore.ThrowExceptions)
throw AlreadyUsedFieldException(field);
else
return false;
}
else
{
MySqlWhere whereStatment = new MySqlWhere();
whereStatment.Connector = nextConnector;
whereStatment.Field = field;
whereStatment.Type = MySqlWhereType.Different;
whereStatment.Value = value;
this.whereStatments.Add(field, whereStatment);
return true;
}
}
public void And()
{
this.nextConnector = MySqlWhereConnector.And;
}
public void Or()
{
this.nextConnector = MySqlWhereConnector.None;
}
public void Execute()
{
using (MySqlConnection dbConnection = MySqlCore.GetNewConnection())
{
using (MySqlCommand cmd = dbConnection.CreateCommand())
{
switch (commandType)
{
#region Insert
case MySqlCommandType.Insert:
{
StringBuilder tempFields = new StringBuilder();
StringBuilder tempValues = new StringBuilder();
bool started = false;
foreach (KeyValuePair<string, object> pair in this.insertValues)
{
if (!started)
{
tempFields.Append(pair.Key);
tempValues.Append('?' + pair.Key);
started = true;
}
else
{
tempFields.Append("," + pair.Key);
tempValues.Append(",?" + pair.Key);
}
cmd.Parameters.AddWithValue('?' + pair.Key, pair.Value);
}
this.command.Replace("<F>", tempFields.ToString());
this.command.Replace("<V>", tempValues.ToString());
cmd.CommandText = this.command.ToString();
cmd.ExecuteNonQuery();
break;
}
#endregion
#region Update
case MySqlCommandType.Update:
{
bool started = false;
foreach (KeyValuePair<string, object> pair in insertValues)
{
if (!started)
{
this.command.Append(" Set " + pair.Key + "=?" + pair.Key);
started = true;
}
else
{
this.command.Append(',' + pair.Key + "=?" + pair.Key );
}
cmd.Parameters.AddWithValue('?' + pair.Key, pair.Value);
}
foreach (KeyValuePair<string, MySqlWhere> whereStatment in this.whereStatments)
{
if (whereStatment.Value.Connector == MySqlWhereConnector.And)
this.command.Append(" And");
else if (whereStatment.Value.Connector == MySqlWhereConnector.Or)
this.command.Append(" Or");
else
this.command.Append(" Where");
this.command.Append(" " + whereStatment.Key);
if (whereStatment.Value.Type == MySqlWhereType.Equal)
this.command.Append("=?1");
else if (whereStatment.Value.Type == MySqlWhereType.Different)
this.command.Append("<>?1");
this.command.Append(whereStatment.Key);
cmd.Parameters.AddWithValue("?1" + whereStatment.Key, whereStatment.Value.Value);
}
cmd.CommandText = this.command.ToString();
cmd.ExecuteNonQuery();
break;
}
#endregion
#region Delete
case MySqlCommandType.Delete:
{
foreach(string field in this.insertValues.Keys)
{
this.command.Replace("<F>", field);
this.command.Replace("<V>", "?" + field);
cmd.Parameters.AddWithValue("?" + field, this.insertValues[field]);
break;
}
cmd.CommandText = this.command.ToString();
cmd.ExecuteNonQuery();
break;
}
#endregion
}
Console.WriteLine(cmd.CommandText);
}
}
}
public void BeginExecute()
{
Action asyncExecute = new Action(Execute);
asyncExecute.BeginInvoke(EndExecute, null);
}
private void EndExecute(IAsyncResult result)
{
}
private Exception WrongTypeException(string invokedMethod, string allowedType)
{
return new Exception("The method " + invokedMethod + " is allowed only when the MySqlWriter's type is " + allowedType);
}
private Exception AlreadyChosenTableException()
{
return new Exception("A table is already chosen for the " + this.commandType.ToString() + " query");
}
private Exception AlreadyUsedFieldException(string field)
{
return new Exception("The field " + field + " is already in use, check for repeated " + commandType.ToString() + " or where statments");
}
}
}
MySqlEnums//same than before, a few enums added
Code:
/*****************************************************************************
* Author: Caparzo/U2_Caparzo.
* Code written for the project MySqlWrapper.
*
* Date: 10/05/2013
* Hour: 1:20
*
* Feel free to use or redistribute this class with any project, but please
* keep this header so credits still goes to the coder of the class.
*****************************************************************************/
using System;
namespace MySqlWrapper
{
public enum MySqlProtocol
{
Tcp,
NamedPipe
}
public enum MySqlCommandType
{
Insert,
Update,
Delete
}
public enum MySqlWhereType
{
Equal,
Different
}
public enum MySqlWhereConnector
{
None,
And,
Or
}
}
MySqlReader//Same than before for the moment :/
Code:
/*****************************************************************************
* Author: Caparzo/U2_Caparzo.
* Code written for the project MySqlWrapper.
*
* Date: 10/05/2013
* Hour: 1:20
*
* Feel free to use or redistribute this class with any project, but please
* keep this header so credits still goes to the coder of the class.
*****************************************************************************/
using System;
using System.Text;
using MySql.Data.MySqlClient;
namespace MySqlWrapper
{
/// <summary>
/// Wrapper for the MySqlDataReader class.
/// </summary>
public class MySqlReader
{
#region private/protected members
private StringBuilder command;
private MySqlDataReader reader;
private MySqlCommand cmd;
#endregion
#region constructors
public MySqlReader()
{
command = new StringBuilder("SELECT * FROM <T>");
cmd = MySqlCore.GetNewConnection().CreateCommand();
}
#endregion
#region methods
/// <summary>
/// Select the table that contains the data that will be read
/// </summary>
/// <param name="Table">Table name</param>
/// <returns></returns>
public MySqlReader Select(string Table)
{
command.Replace("<T>", Table);
return this;
}
/// <summary>
/// Select the column that contains the needed data
/// </summary>
/// <param name="Column">Column name</param>
/// <returns></returns>
public MySqlReader SelectColumn(string Column)
{
command.Replace("*", Column);
return this;
}
public MySqlReader Where(string Column, object value)
{
command.Append(" where " + Column + "=?" + Column);
cmd.Parameters.AddWithValue('?' + Column, value);
return this;
}
public void Execute()
{
cmd.CommandText = command.ToString();
reader = cmd.ExecuteReader();
}
public MySqlReader ReadSByte(string Column, out sbyte value)
{
value = default(sbyte);
if (reader.Read())
value = reader.GetSByte(Column);
return this;
}
public MySqlReader ReadByte(string Column, out byte value)
{
value = default(byte);
if (reader.Read())
value = reader.GetByte(Column);
return this;
}
public MySqlReader ReadInt16(string Column, out Int16 value)
{
value = default(short);
if (reader.Read())
value = reader.GetInt16(Column);
return this;
}
public MySqlReader ReadUInt16(string Column, out UInt16 value)
{
value = default(ushort);
if (reader.Read())
value = reader.GetUInt16(Column);
return this;
}
public MySqlReader ReadInt32(string Column, out Int32 value)
{
value = default(int);
if (reader.Read())
value = reader.GetInt32(Column);
return this;
}
public MySqlReader ReadUInt32(string Column, out UInt32 value)
{
value = default(uint);
if (reader.Read())
value = reader.GetUInt32(Column);
return this;
}
public MySqlReader ReadInt64(string Column, out Int64 value)
{
value = default(long);
if (reader.Read())
value = reader.GetInt64(Column);
return this;
}
public MySqlReader ReadUInt64(string Column, out UInt64 value)
{
value = default(ulong);
if (reader.Read())
value = reader.GetUInt64(Column);
return this;
}
public MySqlReader ReadString(string Column, out string value)
{
value = default(string);
if (reader.Read())
value = reader.GetString(Column);
return this;
}
public MySqlReader ReadBool(string Column, out bool value)
{
value = default(bool);
if (reader.Read())
value = reader.GetBoolean(Column);
return this;
}
public MySqlReader ReadDateTime(string Column, out DateTime value)
{
value = default(DateTime);
if (reader.Read())
value = reader.GetDateTime(Column);
return this;
}
/// <summary>
/// Free the resources used by the MySQLReader
/// </summary>
public void Dispose()
{
cmd.Dispose();
cmd.Connection.Dispose();
reader.Dispose();
}
#endregion
}
}








