Good morning (10:44 am here ;P)
I've build a simple mysql pool handler...
NewConnection method:
MyConnection Class:
Main Handler:
I hope someone finds it usefull ;P
I'll improve when i get some free time...
P.S: New ideas are always welcome...
I've build a simple mysql pool handler...
NewConnection method:
Code:
public static MySqlConnection NewConnection()
{
try
{
return new MySqlConnection("Server=" + SERVER + ";Database='" + DATA_BASE + "';Username='" + USER_NAME + "';Password='" + PASSWORD + "'");
}
catch (Exception e) { Console.WriteLine(e.ToString()); return null; }
}
Code:
public class MyConnection
{
public int m_Id;
public MySqlConnection m_Conn;
public MyConnection(int nId)
{
m_Id = nId;
m_Conn = Information.NewConnection();
}
}
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using MySql.Data.MySqlClient;
using System.Data;
namespace MsgServer.Common.MYSQL
{
public class MySqlPool
{
public MyConnection[] Connection_Pool = null;
int m_Size = 50;//Default size
int m_Counter = 0;
/// <summary>
/// Create a new mysqlpool instance
/// </summary>
public MySqlPool(int max_size)
{
if (max_size > 50)
m_Size = max_size;
Connection_Pool = new MyConnection[m_Size];
}
/// <summary>
/// Store a connection to the mysql connection pool.
/// </summary>
public bool ToPool(MyConnection pConn)
{
if (Contains(pConn.m_Id))
return true;
if (m_Counter + 1 >= m_Size)
{
Console.WriteLine("[MySql] Connection pool handler has reached the max pool size.");
return false;
}
Console.WriteLine("[MySql] Connection pool handler has stored a new mysql connection.");
Connection_Pool[m_Counter] = pConn;
m_Counter++;
return true;
}
/// <summary>
/// Return a stored connection from the connection pool.
/// </summary>
public MyConnection FromPool()
{
MyConnection pConn = null;
Boolean Founded = false;
for (int i = 0; i < m_Counter; i++)
{
if (Connection_Pool[i] == null)
continue;
switch (Connection_Pool[i].m_Conn.State)
{
case ConnectionState.Broken:
pConn = Connection_Pool[i];
pConn.m_Conn.Close();
Founded = true;
break;
case ConnectionState.Closed:
pConn = Connection_Pool[i];
Founded = true;
break;
}
if (Founded)
break;
}
if (pConn == null)
{
try { pConn = new MyConnection(m_Counter + 1); }
catch (Exception Exception) { Console.WriteLine(Exception); }
}
return pConn;
}
/// <summary>
/// Check if the connection already exist into the connection pool.
/// </summary>
public bool Contains(int m_Id)
{
Boolean Cont = false;
for (int i = 0; i < m_Counter; i++)
{
if (Connection_Pool[i] == null)
continue;
if (Connection_Pool[i].m_Id == m_Id)
{
Cont = true;
break;
}
}
return Cont;
}
}
}
I'll improve when i get some free time...
P.S: New ideas are always welcome...