voidConnPool::InitConnection(int iInitialSize) { Connection*conn; pthread_mutex_lock(&lock); for(inti=0;i<iInitialSize;i++) { conn=this->CreateConnection(); if(conn){ connList.push_back(conn); ++(this->curSize); } else { perror("创建CONNECTION出错"); } } pthread_mutex_unlock(&lock); } //创建连接,返回一个Connection Connection*ConnPool::CreateConnection(){ Connection*conn; try{ conn=driver->connect(this->url,this->username,this->password);//建立连接 returnconn; } catch(sql::SQLException&e) { perror("创建连接出错"); returnNULL; } catch(std::runtime_error&e) { perror("运行时出错"); returnNULL; } } //在连接池中获得一个连接 Connection*ConnPool::GetConnection(){ Connection*con; pthread_mutex_lock(&lock); if(connList.size()>0)//连接池容器中还有连接 { con=connList.front();//得到第一个连接 connList.pop_front();//移除第一个连接 if(con->isClosed())//如果连接已经被关闭,删除后重新建立一个 { deletecon; con=this->CreateConnection(); } //如果连接为空,则创建连接出错 if(con==NULL) { --curSize; } pthread_mutex_unlock(&lock); returncon; } else{ if(curSize< maxSize){//还可以创建新的连接 con= this->CreateConnection(); if(con){ ++curSize; pthread_mutex_unlock(&lock); returncon; } else{ pthread_mutex_unlock(&lock); returnNULL; } } else{//建立的连接数已经达到maxSize pthread_mutex_unlock(&lock); returnNULL; } } } //回收数据库连接 voidConnPool::ReleaseConnection(sql::Connection * conn){ if(conn){ pthread_mutex_lock(&lock); connList.push_back(conn); pthread_mutex_unlock(&lock); } } //连接池的析构函数 ConnPool::~ConnPool() { this->DestoryConnPool(); } //销毁连接池,首先要先销毁连接池的中连接 voidConnPool::DestoryConnPool(){ list<Connection*>::iterator icon; pthread_mutex_lock(&lock); for(icon=connList.begin();icon!=connList.end();++icon) { this->DestoryConnection(*icon);//销毁连接池中的连接 } curSize=0; connList.clear();//清空连接池中的连接 pthread_mutex_unlock(&lock); } //销毁一个连接 voidConnPool::DestoryConnection(Connection* conn) { if(conn) { try{ conn->close(); } catch(sql::SQLException&e) { perror(e.what()); } catch(std::exception&e) { perror(e.what()); } deleteconn; } } |