// TraceList.cpp : implementation file
//
#include "stdafx.h"
#include "ODBCPool.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CCODBCPool
CODBCPool cp;
CODBCPool::CODBCPool()
{
InitializeCriticalSection(&m_csList);
}
CODBCPool::CODBCPool(CString dsn)
{
InitializeCriticalSection(&m_csList);
s_dsn=dsn;
}
void CODBCPool::FreeOdbc(int type)
{
ODBCPOOLLIST *pl;
if(type==0)
pl=&m_lsIdleList;
else
pl=&m_lsBusyList;
CDatabase* pMySql = NULL;
POSITION pos = pl->GetHeadPosition();
while (pos!=NULL)
{
pMySql=pl->GetAt(pos);
if(pMySql!=NULL)
{
pMySql->Close();
delete pMySql;
#if MYDGB
CString os;
os.Format("end db in idle =%x",pMySql);
WtMonitor(os);
#endif
pMySql=NULL;
}
pl->GetNext(pos);
}
pl->RemoveAll();
}
CODBCPool::~CODBCPool()
{
FreeOdbc(0);
FreeOdbc(1);
DeleteCriticalSection(&m_csList);
}
int CODBCPool::GetIdleNum()
{
int ri=0;
EnterCriticalSection(&m_csList);
POSITION pos = m_lsIdleList.GetHeadPosition();
while (pos!=NULL)
{
m_lsIdleList.GetNext(pos);
ri++;
}
LeaveCriticalSection(&m_csList);
return ri;
}
void CODBCPool::SetDSN(CString dsn)
{
FreeOdbc(0);
s_dsn=dsn;
}
BOOL CODBCPool::ConnectToDB(int num)
{
CDatabase* pMySql = NULL;
BOOL rt=FALSE;
int ri=0;
if(num>1)ri=GetIdleNum();
for(int i=0;i<num-ri;i++)
{
pMySql=new CDatabase();
TRY
{
pMySql->OpenEx(s_dsn,CDatabase::noOdbcDialog|CDatabase::useCursorLib);//
}
CATCH(CDBException, e)
{
#if MYDGB
WtMonitor(e->m_strError);
#endif
delete pMySql;
pMySql=NULL;
}
END_CATCH
if(pMySql!=NULL)
{
#if MYDGB
CString os;
os.Format("connect db=%x",pMySql);
WtMonitor(os);
#endif
EnterCriticalSection(&m_csList);
m_lsIdleList.AddHead(pMySql);
LeaveCriticalSection(&m_csList);
rt=TRUE;
}
}
return rt;
}
void CODBCPool::SetIdleMysql(CDatabase* pMySql)
{
POSITION pos;
if(pMySql==NULL)return;
EnterCriticalSection(&m_csList);
pos=m_lsBusyList.Find(pMySql);
if(pos!=NULL)
{
m_lsBusyList.RemoveAt(pos);
m_lsIdleList.AddTail(pMySql);
#if MYDGB
CString os;
os.Format("free db=%x",pMySql);
WtMonitor(os);
#endif
}
LeaveCriticalSection(&m_csList);
}
CDatabase* CODBCPool::GetIdleMySql()
{
CDatabase* pMySql = NULL;
EnterCriticalSection(&m_csList);
if(!m_lsIdleList.IsEmpty())
{
pMySql = m_lsIdleList.GetHead();
m_lsIdleList.RemoveHead();
m_lsBusyList.AddHead(pMySql);
}
else
{
pMySql = NULL;
}
LeaveCriticalSection(&m_csList);
if(pMySql==NULL)//没有找到 则 增加一个连接入队
{
#if MYDGB
WtMonitor("no one");
#endif
if(ConnectToDB(1))
pMySql=GetIdleMySql();
}
else
{
#if MYDGB
CString os;
os.Format("getdb=%x",pMySql);
WtMonitor(os);
#endif
}
return pMySql;
}