MySQL由于它本身的小巧和操作的高效, 在数据库应用中越来越多的被采用.我在开发一个P2P应用的时候曾经使用MySQL来保存P2P节点,由于P2P的应用中,结点数动辄上万个,而且节点变化频繁,因此一定要保持查询和插入的高效.以下是我在使用过程中做的提高效率的三个有效的尝试.
bool CDBManager::Connect(char * host /* = "localhost" */, char * user /* = "chenmin" */, \
char * password /* = "chenmin" */, char * database /* = "HostCache" */)
{
CDBParameter * lpDBParam = new CDBParameter();
lpDBParam->host = host;
lpDBParam->user = user;
lpDBParam->password = password;
lpDBParam->database = database;
lpDBParam->port = 0;
lpDBParam->unix_socket = NULL;
lpDBParam->client_flag = 0;
try
{
//连接
for(int index = 0; index < CONNECTION_NUM; index++)
{
MYSQL * pConnectHandle = mysql_init((MYSQL*) 0); //初始化连接句柄
if(!mysql_real_connect(pConnectHandle, lpDBParam->host, lpDBParam->user, lpDBParam->password,\
lpDBParam->database,lpDBParam->port,lpDBParam->unix_socket,lpDBParam->client_fla))
return false;
//加入到空闲队列中
m_lsIdleList.push_back(pConnectHandle);
}
}
catch(...)
{
return false;
}
return true;
}
//提取一个空闲句柄供使用
MYSQL * CDBManager::GetIdleConnectHandle()
{
MYSQL * pConnectHandle = NULL;
m_ListMutex.acquire();
if(m_lsIdleList.size())
{
pConnectHandle = m_lsIdleList.front();
m_lsIdleList.pop_front();