Qt 数据库连接池

#ifndef SQLITE_H
#define SQLITE_H

#include 
#include 
#include 
#include 
#include 
#include 
#include "../config.h"
#include "sqlInfo.h"

class SqLite {
public:
    static SqLite &instance() {
        // 使用单例模式保证只创建一个连接池对象
        static SqLite pool;
        return pool;
    }

    QSqlDatabase getConnection() {
        // 获取连接
        m_mutex.lock();
        if (m_connections.isEmpty()) {
            addConnections(10);
        }
        QSqlDatabase db;
        if (QSqlDatabase::contains("qt_sql_default_connection")) {
            db = QSqlDatabase::database("qt_sql_default_connection");
        } else {
            db = m_connections.dequeue();
        }
        m_mutex.unlock();

        // 如果连接断开,则重新连接
        if (!db.isOpen()) {
            db.open();
        }
        return db;
    }

    void releaseConnection(QSqlDatabase db) {
        // 释放连接
        m_mutex.lock();
        db.close();
        m_connections.enqueue(db);
        m_mutex.unlock();
    }

    static void init_table() {
        QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
        db.setDatabaseName(DB_PATH);
        if (!db.open()) {
            qDebug() << "Failed to open database:" << db.lastError().text();
        }
        QSqlQuery query(db);
        // 初始化数据库
        query.exec(CREATE_USER_TABLE);
        query.exec(CREATE_USER_INDEX);
        query.exec(CREATE_ROLE_TABLE);
        db.close();
    };

private:
    SqLite() {
        // 初始化连接池
        addConnections(30);
    }

    void addConnections(int count) {
        // 创建连接
        for (int i = 0; i < count; i++) {
            QSqlDatabase db;
            if (QSqlDatabase::contains("qt_sql_default_connection")) {
                db = QSqlDatabase::database("qt_sql_default_connection");
            } else {
                db = QSqlDatabase::addDatabase("QSQLITE");
            }
            db.setDatabaseName(DB_PATH);
            if (db.open()) {
                m_connections.enqueue(db);
            } else {
                qDebug() << "Failed to open database:" << db.lastError().text();
            }
        }
    }


private:
    QMutex m_mutex;
    QQueue m_connections;
};

#endif // SQLITE_H

你可能感兴趣的:(c++,数据库)