MySql数据库连接池

项目场景:

单例模式,并能正确地析构。智能指针的使用。


connection_pool.h

/*
 *File: connection_pool.h
 *Author: fengwei
 */

#ifndef _CONNECTION_POOL_H  
#define _CONNECTION_POOL_H  

#include <mysql/jdbc.h>
#include <windows.h>  
#include <list>  
#include <iostream>
using namespace std;
using namespace sql;
/*通过写一个加锁的类来对共享的数据进行有效的安全控制,防止内存错误*/
class MTCMutex
{
public:
    MTCMutex() :_mutex(NULL)
    {
        this->_mutex = CreateMutex(NULL, FALSE, NULL);
        if (this->_mutex == NULL)
            throw std::exception("CreateMutex 失败!");
    }
    virtual ~MTCMutex()
    {
        if (this->_mutex)
        {

            CloseHandle(this->_mutex);
            std::cout << "mutex" << std::endl;
            this->_mutex = NULL;
        }
    }
    MTCMutex(const MTCMutex& mutex) { *this = mutex; }
    MTCMutex& operator=(const MTCMutex& other)
    {
        if (this != &other)
        {
            this->_mutex = other._mutex;
        }
        return *this;
    }
private:
    HANDLE _mutex;


public:
    BOOL Lock()
    {
        DWORD dwRet = ::WaitForSingleObject(this->_mutex, INFINITE);
        if (dwRet == WAIT_OBJECT_0 || dwRet == WAIT_ABANDONED)
            return TRUE;
        else
            return FALSE;
    }


    void UnLock()
    {
        ReleaseMutex(this->_mutex);
    }
};
class ConnPool {
private:
    int curSize; //当前已建立的数据库连接数量  
    int maxSize; //连接池中定义的最大数据库连接数  
    string username;
    string password;
    string url;
    list<Connection*> connList; //连接池的容器队列  STL list 双向链表
    static MTCMutex lock; //线程锁  
    static ConnPool *connPool;
    Driver*driver;

    Connection*CreateConnection(); //创建一个连接  
    void InitConnection(int iInitialSize); //初始化数据库连接池  
    void DestoryConnection(Connection *conn); //销毁数据库连接对象  
    void DestoryConnPool(); //销毁数据库连接池  
    ConnPool(string url, string user, string password, int maxSize); //构造方法  

    class GGarbo
    {
    public:
        ~GGarbo()
        {
 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值