C++手写数据库连接池

C++手写数据库连接池

简介

大家好,我是天津市大学软件学院23届C++后端开发练习生飞猪6。

这篇文章详细介绍C++实现数据库连接。

关键技术点

  • MySQL数据库编程
  • 单例模式
  • queue队列容器
  • C++11多线程编程:线程互斥、线程同步通信和unique_lock
  • 基于CAS的原子整型
  • lambda表达式
  • 生产者-消费者模型

项目背景

为了提高MySQL数据库(基于C/S设计)的访问瓶颈,除了在服务器端增加缓存服务器缓存常用的数据 之外(例如redis),还可以增加连接池,来提高MySQL Server的访问效率,在高并发情况下,大量的TCP三次握手、MySQL Server连接认证、MySQL Server关闭连接回收资源和TCP四次挥手所耗费的性能时间也是很明显的,增加连接池就是为了减少这一部分的性能损耗。

连接池功能点介绍

连接池一般包含了数据库连接所用的ip地址、port端口号、用户名和密码以及其它的性能参数,例如初 始连接量,最大连接量,最大空闲时间、连接超时时间等,该项目是基于C++语言实现的连接池,主要 也是实现以上几个所有连接池都支持的通用基础功能。

**初始连接量(initSize):**表示连接池事先会和MySQL Server创建initSize个数的connection连接,当 应用发起MySQL访问时,不用再创建和MySQL Server新的连接,直接从连接池中获取一个可用的连接 就可以,使用完成后,并不去释放connection,而是把当前connection再归还到连接池当中。

**最大连接量(maxSize):**当并发访问MySQL Server的请求增多时,初始连接量已经不够使用了,此 时会根据新的请求数量去创建更多的连接给应用去使用,但是新创建的连接数量上限是maxSize,不能 无限制的创建连接,因为每一个连接都会占用一个socket资源,一般连接池和服务器程序是部署在一台 主机上的,如果连接池占用过多的socket资源,那么服务器就不能接收太多的客户端请求了。当这些连 接使用完成后,再次归还到连接池当中来维护。

**最大空闲时间(maxIdleTime):**当访问MySQL的并发请求多了以后,连接池里面的连接数量会动态 增加,上限是maxSize个,当这些连接用完再次归还到连接池当中。如果在指定的maxIdleTime里面, 这些新增加的连接都没有被再次使用过,那么新增加的这些连接资源就要被回收掉,只需要保持初始连 接量initSize个连接就可以了。

**连接超时时间(connectionTimeout):**当MySQL的并发请求量过大,连接池中的连接数量已经到达 maxSize了,而此时没有空闲的连接可供使用,那么此时应用从连接池获取连接无法成功,它通过阻塞 的方式获取连接的时间如果超过connectionTimeout时间,那么获取连接失败,无法访问数据库。

功能实现设计

ConnectionPool.cpp和ConnectionPool.h:连接池代码实现

Connection.cpp和Connection.h:数据库操作代码、增删改查代码实现

连接池主要包含了以下功能点:

1.连接池只需要一个实例,所以ConnectionPool以单例模式进行设计

2.从ConnectionPool中可以获取和MySQL的连接Connection

3.空闲连接Connection全部维护在一个线程安全的Connection队列中,使用线程互斥锁保证队列的线 程安全

4.如果Connection队列为空,还需要再获取连接,此时需要动态创建连接,上限数量是maxSize

5.队列中空闲连接时间超过maxIdleTime的就要被释放掉,只保留初始的initSize个连接就可以了,这个 功能点肯定需要放在独立的线程中去做

6.如果Connection队列为空,而此时连接的数量已达上限maxSize,那么等待connectionTimeout时间 如果还获取不到空闲的连接,那么获取连接失败,此处从Connection队列获取空闲连接,可以使用带 超时时间的mutex互斥锁来实现连接超时时间

7.用户获取的连接用shared_ptr智能指针来管理,用lambda表达式定制连接释放的功能(不真正释放 连接,而是把连接归还到连接池中)

8.连接的生产和连接的消费采用生产者-消费者线程模型来设计,使用了线程间的同步通信机制条件变量 和互斥锁

MySQL数据库编程

这里的MySQL数据库编程直接采用oracle公司提供的MySQL C/C++客户端开发包,在VS上需要进行相 应的头文件和库文件的配置,如下:

1.右键项目 - C/C++ - 常规 - 附加包含目录,填写mysql.h头文件的路径

2.右键项目 - 链接器 - 常规 - 附加库目录,填写libmysql.lib的路径

3.右键项目 - 链接器 - 输入 - 附加依赖项,填写libmysql.lib库的名字

4.把libmysql.dll动态链接库(Linux下后缀名是.so库)放在工程目录下

代码实现

日志记录公共类 public.h

/**
 * @Description 输出程序错误日志记录 __FILE__ 报错文件名 __LINE__报错代码发生在第几行
 * @Version 1.0.0
 * @Date 2024/8/19 23:11
 * @Github https://github.com/Programmer-Kenton
 * @Author Kenton
 */

#pragma once
#ifndef DATABASEPOOL_PUBLIC_H
#define DATABASEPOOL_PUBLIC_H
#include <string>
#include <iostream>


#define  LOG(str) \
    std::cout << __FILE__ << ":" << __LINE__ << " " << \
    __TIMESTAMP__ << ":" << str << std::endl;
#endif //DATABASEPOOL_PUBLIC_H

数据库连接对象 Connection.h/cpp

/**
 * @Description 实现数据库连接操作
 * @Version 1.0.0
 * @Date 2024/8/19 23:05
 * @Github https://github.com/Programmer-Kenton
 * @Author Kenton
 */

#pragma once
#ifndef DATABASEPOOL_CONNECTION_H
#define DATABASEPOOL_CONNECTION_H


#include <iostream>
#include <ctime>
#include "public.h"
#include "mysql.h"

using namespace std;


class Connection {

public:
    // 初始化数据库连接
    Connection();

    // 释放数据库连接
    ~Connection();

    // 连接数据库
    bool connect(string ip, unsigned short port, string user, string password, string dbname);

    // 更新操作
    bool update(string sql);

    // 查询操作
    MYSQL_RES* query(string sql);

    // 刷新链接的起始的空闲时间点
    void refreshAliveTime();

    // 返回存活的时间
    clock_t getAliceTime() const;

private:
    // 表示和MYSQL Server的一条连接
    MYSQL* _conn;

    // 记录进入空闲状态后的起始存活时间
    clock_t _alivetime;
};

#endif //DATABASEPOOL_CONNECTION_H




#include "Connection.h"

Connection::Connection() {
	// 初始化连接数据库
	_conn = mysql_init(nullptr);
}

Connection::~Connection() {
	if (_conn != nullptr) {
		mysql_close(_conn);
	}
}

bool Connection::connect(string ip, unsigned short port, string username, string password, string dbname) {
	MYSQL* p = mysql_real_connect(_conn, ip.c_str(), username.c_str(), password.c_str(), dbname.c_str(), port, nullptr, 0);
	return p != nullptr;
}

bool Connection::update(string sql) {
	if (mysql_query(_conn,sql.c_str())) {
		LOG("更新失败:" + sql);
		return false;
	}
	return true;
}

MYSQL_RES* Connection::query(string sql) {
	if (mysql_query(_conn, sql.c_str())) {
		LOG("查询失败:" + sql);
		return nullptr;
	}
	return mysql_use_result(_conn);
}

void Connection::refreshAliveTime() {
	// 返回的是从程序开始执行到调用 clock() 函数时所消耗的 CPU 时间
	_alivetime = clock();
}

clock_t Connection::getAliceTime() const {
	return clock() - _alivetime;
}

数据库连接池对象 ConnectionPool.h/cpp

/**
 * @Description 实现连接池功能模块
 * @Version 1.0.0
 * @Date 2024/8/19 23:05
 * @Github https://github.com/Programmer-Kenton
 * @Author Kenton
 */

#pragma once
#ifndef DATABASEPOOL_COMMONCONNECTIONPOOL_H
#define DATABASEPOOL_COMMONCONNECTIONPOOL_H

#include <string>
#include <queue>
#include <mutex>
#include <atomic>
#include <thread>
#include <memory>
#include <functional>
#include <condition_variable>
#include <stdio.h>
#include "public.h"
#include "Connection.h"

using namespace std;

class ConnectionPool {

public:
    // 获取连接池对象实例
    static ConnectionPool* getConnectionPool();

    // 从外部提供接口 从连接池中获取一个可用的空闲连接
    shared_ptr<Connection> getConnection();


private:
    // 单例 构造函数私有化
    ConnectionPool();

    // 从配置文件中加载配置项
    bool loadConfigFile();

    // mysql的ip地址
    string _ip;

    // mysql的端口号
    unsigned short _port;

    // 数据库连接用户
    string _username;

    // mysql连接密码
    string _password;

    // 连接的数据库名
    string _dbname;

    // 连接池的初始连接量
    int _initSize;

    // 连接池的最大连接量
    int _maxSize;

    // 连接池最大空闲时间
    int _maxIdleTime;

    // 连接池获取连接的超时时间
    int _connectionTimeout;

    // 存储mysql连接的队列
    queue<Connection*> _connectionQue;

    // 维护连接队列的线程安全互斥锁
    mutex _queueMutex;

    // 记录连接所创建的connection连接的总数量
    atomic_int _connectionCnt;

    // 运行在独立的线程中 专门负责生产新连接
    void produceConnectionTask();

    // 扫描超过maxIdleTime时间的空闲连接 进行连接回收
    void scannerConnectionTask();

    // 设置条件变量 用于连接生产线程和连接消费线程的通信
    condition_variable cv;
};


#endif //DATABASEPOOL_COMMONCONNECTIONPOOL_H

#include "ConnectionPool.h"

ConnectionPool* ConnectionPool::getConnectionPool() {
	static ConnectionPool pool;
	return &pool;
}

shared_ptr<Connection> ConnectionPool::getConnection() {
	// 消费者抢到锁
	unique_lock<mutex> lock(_queueMutex);
	// 脱离作用域 锁失效
	while (_connectionQue.empty()) {
		// 等待连接超时
		if (cv_status::timeout == cv.wait_for(lock,chrono::milliseconds(_connectionTimeout))) {
			if (_connectionQue.empty()) {
				LOG("获取空闲连接超时...获取连接失败\n");
				return nullptr;
			}
		}
	}

	/**
	* 智能指针析构时会把connection资源直接delete掉
	* 这里需要自定义shared_ptr释放资源的方式 把connection直接归还到queue当中
	*/
	shared_ptr<Connection> sp(_connectionQue.front(), [&](Connection* pcon) {
		// 保障线程安全
		unique_lock<mutex> lock(_queueMutex);
		pcon->refreshAliveTime();
		_connectionQue.push(pcon);
	});
	_connectionQue.pop();
	cv.notify_all();
	return sp;
}

ConnectionPool::ConnectionPool() {
	// 加载数据库配置项
	if (!loadConfigFile()) {
		return;
	}

	// 创建初始数量的连接
	for (size_t i = 0; i < _initSize; i++) {
		Connection* p = new Connection();
		// 每创建一个数据库连接对象就进行连接
		p->connect(_ip, _port, _username, _password, _dbname);
		// 刷新开始空闲的起始时间
		p->refreshAliveTime();
		// 连接对象放入队列
		_connectionQue.push(p);
		// 已创建的连接总数量+1
		_connectionCnt++;
	}

	// 启动新的线程作为连接生产者
	thread produce(std::bind(&ConnectionPool::produceConnectionTask, this));
	// 分离线程
	produce.detach();

	// 启动新的线程 扫描多余的空闲连接超过maxIdleTime的空闲连接进行回收
	thread scanner(std::bind(&ConnectionPool::scannerConnectionTask, this));
}

bool ConnectionPool::loadConfigFile() {
	FILE* pf = fopen("mysql.ini", "r");
	if (pf == nullptr) {
		LOG("mysql.ini file is not exist");
		return false;
	}

	while (!feof(pf)) {
		char line[1024] = { 0 };
		fgets(line, 1024, pf);
		string str = line;
		// 从0下标开始找到第一个出现'='的下标
		int idx = str.find('=', 0);
		// 无效的配置
		if (idx == -1) {
			continue;
		}
		int endidx = str.find('\n', idx);
		string key = str.substr(0, idx);
		string value = str.substr(idx + 1, endidx - idx - 1);

		// cout << endl;
		if (key == "ip") {
			_ip = value;
		} else if (key == "port") {
			_port = atoi(value.c_str());
		} else if (key == "username") {
			_username = value;
		} else if (key == "initSize") {
			_initSize = atoi(value.c_str());
		} else if (key == "maxSize") {
			_maxSize = atoi(value.c_str());
		} else if (key == "maxIdleTime") {
			_maxIdleTime = atoi(value.c_str());
		} else if (key == "connectionTimeout") {
			_connectionTimeout = atoi(value.c_str());
		} else if (key == "dbname") {
			_dbname = key;
		}
	}


	return true;
}

void ConnectionPool::produceConnectionTask() {

	for (;;) {
		// 生产者抢到锁
		unique_lock<mutex> lock(_queueMutex);
		// 另一个作用域 释放锁
		while (!_connectionQue.empty()) {
			// 队列不空 此处生产线程进入等待状态
			cv.wait(lock);
		}

		// 连接数量没有到达上限继续创建
		if (_connectionCnt < _maxSize) {
			Connection* p = new Connection();
			p->connect(_ip, _port, _username, _password, _dbname);
			_connectionQue.push(p);
			p->refreshAliveTime();
			_connectionCnt++;
		}

		// 通知消费者线程
		cv.notify_all();
	}
}

void ConnectionPool::scannerConnectionTask() {
	for (;;) {
		// 通过sleep模拟定时效果
		this_thread::sleep_for(chrono::seconds(_maxIdleTime));
		// 扫描整个队列 释放多余连接
		unique_lock<mutex> lock(_queueMutex);
		while (_connectionCnt > _initSize) {
			Connection* p = new Connection();
			if (p->getAliceTime() > (_maxIdleTime * 1000)) {
				_connectionQue.pop();
				_connectionCnt--;
				delete p;
			} else {
				// 队列先进先出 如果头个连接对象都没有超时 后面的连接对象一定没有超时
				break;
			}
		}
	}
}

数据库配置文件mysql.ini

# 数据库连接池的配置文件
ip=你的数据库服务器ip
port=3306
username=数据库用户
password=数据库登录密码
dbname=testSql
initSize=10
maxSize=1024
# 最大空闲默认时间单位是秒
maxIdleTime=60
# 连接超时时间单位是毫秒
connectionTimeout=100

数据库建表

create database testSql;

use user;

create table user(
    id int null
);

压力测试

验证数据的插入操作所花费的时间,第一次测试使用普通的数据库访问操作,第二次测试使用带连接池 的数据库访问操作,对比两次操作同样数据量所花费的时间,性能压力测试结果如下:

数据量未使用连接池花费时间使用连接池花费时间
1000单线程:1600ms 四线程:单线程:988ms 四线程:327ms
5000单线程:8934ms 四线程:单线程:5425ms 四线程:1879ms
10000单线程:12067ms 四线程:单线程:8703 四线程:3563ms

测试主函数如下

#include "ConnectionPool.h"

int main() {

	// 记录程序开始时间
	clock_t begin = clock();

#if 0
	// 单线程 模拟1000个连接量
	for (int i = 0; i < 1000; i++) {
		Connection conn;
		char sql[1024] = { 0 };
		sprintf(sql, "insert into user(id) values(%d)", i);
		conn.connect("你的数据库服务器ip", 3306, "数据库用户名", "数据库登录密码", "testSql");
		conn.update(sql);
	}


#endif


#if 0

	// 使用连接池单线程 模拟1000个连接量
	ConnectionPool* cp = ConnectionPool::getConnectionPool();
	for (size_t i = 0; i < 1000; i++) {
		char sql[1024] = { 0 };
		sprintf(sql, "insert into user(id) values(%d)", i);
		shared_ptr<Connection> sp = cp->getConnection();
		sp->update(sql);
	}


#endif


#if 0
	// 使用单线程 模拟5000个连接量
	for (int i = 0; i < 5000; i++) {
		Connection conn;
		char sql[1024] = { 0 };
		sprintf(sql, "insert into user(id) values(%d)", i);
		conn.connect("你的数据库服务器ip", 3306, "数据库用户名", "数据库登录密码", "testSql");
		conn.update(sql);
	}

#endif

#if 0
	// 使用连接池单线程 模拟5000个连接量
	ConnectionPool* cp = ConnectionPool::getConnectionPool();
	for (size_t i = 0; i < 5000; i++) {
		char sql[1024] = { 0 };
		sprintf(sql, "insert into user(id) values(%d)", i);
		shared_ptr<Connection> sp = cp->getConnection();
		sp->update(sql);
	}

#endif


#if 0
	// 使用单线程 模拟10000个连接量
	for (int i = 0; i < 10000; i++) {
		Connection conn;
		char sql[1024] = { 0 };
		sprintf(sql, "insert into user(id) values(%d)", i);
		conn.connect("你的数据库服务器ip", 3306, "数据库用户名", "数据库登录密码", "testSql");
		conn.update(sql);
	}

#endif

#if 0
	// 使用连接池单线程 模拟10000个连接量
	ConnectionPool* cp = ConnectionPool::getConnectionPool();
	for (size_t i = 0; i < 10000; i++) {
		char sql[1024] = { 0 };
		sprintf(sql, "insert into user(id) values(%d)", i);
		shared_ptr<Connection> sp = cp->getConnection();
		sp->update(sql);
	}

#endif


#if 0
	// 模拟四线程 模拟1000个连接量 带连接池
	thread t1([]() {
		ConnectionPool* cp = ConnectionPool::getConnectionPool();
		for (size_t i = 0; i < 250; i++) {
			char sql[1024] = { 0 };
			sprintf(sql, "insert into user(id) values(%d)", i);
			shared_ptr<Connection> sp = cp->getConnection();
			sp->update(sql);
		}
	});

	thread t2([]() {
		ConnectionPool* cp = ConnectionPool::getConnectionPool();
		for (size_t i = 0; i < 250; i++) {
			char sql[1024] = { 0 };
			sprintf(sql, "insert into user(id) values(%d)", i);
			shared_ptr<Connection> sp = cp->getConnection();
			sp->update(sql);
		}
	});

	thread t3([]() {
		ConnectionPool* cp = ConnectionPool::getConnectionPool();
		for (size_t i = 0; i < 250; i++) {
			char sql[1024] = { 0 };
			sprintf(sql, "insert into user(id) values(%d)", i);
			shared_ptr<Connection> sp = cp->getConnection();
			sp->update(sql);
		}
	});

	thread t4([]() {
		ConnectionPool* cp = ConnectionPool::getConnectionPool();
		for (size_t i = 0; i < 250; i++) {
			char sql[1024] = { 0 };
			sprintf(sql, "insert into user(id) values(%d)", i);
			shared_ptr<Connection> sp = cp->getConnection();
			sp->update(sql);
		}
	});

	t1.join();
	t2.join();
	t3.join();
	t4.join();

#endif


#if 0
	// 模拟四线程 模拟5000个连接量 带连接池
	thread t1([]() {
		ConnectionPool* cp = ConnectionPool::getConnectionPool();
		for (size_t i = 0; i < 1250; i++) {
			char sql[1024] = { 0 };
			sprintf(sql, "insert into user(id) values(%d)", i);
			shared_ptr<Connection> sp = cp->getConnection();
			sp->update(sql);
		}
		});

	thread t2([]() {
		ConnectionPool* cp = ConnectionPool::getConnectionPool();
		for (size_t i = 0; i < 1250; i++) {
			char sql[1024] = { 0 };
			sprintf(sql, "insert into user(id) values(%d)", i);
			shared_ptr<Connection> sp = cp->getConnection();
			sp->update(sql);
		}
		});

	thread t3([]() {
		ConnectionPool* cp = ConnectionPool::getConnectionPool();
		for (size_t i = 0; i < 1250; i++) {
			char sql[1024] = { 0 };
			sprintf(sql, "insert into user(id) values(%d)", i);
			shared_ptr<Connection> sp = cp->getConnection();
			sp->update(sql);
		}
		});

	thread t4([]() {
		ConnectionPool* cp = ConnectionPool::getConnectionPool();
		for (size_t i = 0; i < 1250; i++) {
			char sql[1024] = { 0 };
			sprintf(sql, "insert into user(id) values(%d)", i);
			shared_ptr<Connection> sp = cp->getConnection();
			sp->update(sql);
		}
		});

	t1.join();
	t2.join();
	t3.join();
	t4.join();

#endif

#if 0
	// 模拟四线程 模拟10000个连接量 带连接池
	thread t1([]() {
		ConnectionPool* cp = ConnectionPool::getConnectionPool();
		for (size_t i = 0; i < 2500; i++) {
			char sql[1024] = { 0 };
			sprintf(sql, "insert into user(id) values(%d)", i);
			shared_ptr<Connection> sp = cp->getConnection();
			sp->update(sql);
		}
		});

	thread t2([]() {
		ConnectionPool* cp = ConnectionPool::getConnectionPool();
		for (size_t i = 0; i < 2500; i++) {
			char sql[1024] = { 0 };
			sprintf(sql, "insert into user(id) values(%d)", i);
			shared_ptr<Connection> sp = cp->getConnection();
			sp->update(sql);
		}
		});

	thread t3([]() {
		ConnectionPool* cp = ConnectionPool::getConnectionPool();
		for (size_t i = 0; i < 2500; i++) {
			char sql[1024] = { 0 };
			sprintf(sql, "insert into user(id) values(%d)", i);
			shared_ptr<Connection> sp = cp->getConnection();
			sp->update(sql);
		}
		});

	thread t4([]() {
		ConnectionPool* cp = ConnectionPool::getConnectionPool();
		for (size_t i = 0; i < 2500; i++) {
			char sql[1024] = { 0 };
			sprintf(sql, "insert into user(id) values(%d)", i);
			shared_ptr<Connection> sp = cp->getConnection();
			sp->update(sql);
		}
		});

	t1.join();
	t2.join();
	t3.join();
	t4.join();

#endif
	
#if 0
	// 模拟四线程 模拟1000个连接量 不带连接池
	thread t1([]() {
		for (int i = 0; i < 250; i++) {
			Connection conn;
			char sql[1024] = { 0 };
			sprintf(sql, "insert into user(id) values(%d)", i);
			conn.connect("你的数据库服务器ip", 3306, "数据库用户名", "数据库登录密码", "testSql");
			conn.update(sql);
		}
		});

	thread t2([]() {
		for (int i = 0; i < 250; i++) {
			Connection conn;
			char sql[1024] = { 0 };
			sprintf(sql, "insert into user(id) values(%d)", i);
			conn.connect("你的数据库服务器ip", 3306, "数据库用户名", "数据库登录密码", "testSql");
			conn.update(sql);
		}
		});

	thread t3([]() {
		for (int i = 0; i < 250; i++) {
			Connection conn;
			char sql[1024] = { 0 };
			sprintf(sql, "insert into user(id) values(%d)", i);
			conn.connect("你的数据库服务器ip", 3306, "数据库用户名", "数据库登录密码", "testSql");
			conn.update(sql);
		}
		});

	thread t4([]() {
		for (int i = 0; i < 250; i++) {
			Connection conn;
			char sql[1024] = { 0 };
			sprintf(sql, "insert into user(id) values(%d)", i);
			conn.connect("你的数据库服务器ip", 3306, "数据库用户名", "数据库登录密码", "testSql");
			conn.update(sql);
		}
		});

	t1.join();
	t2.join();
	t3.join();
	t4.join();

#endif

#if 0
	// 模拟四线程 模拟5000个连接量 不带连接池
	thread t1([]() {
		for (int i = 0; i < 1250; i++) {
			Connection conn;
			char sql[1024] = { 0 };
			sprintf(sql, "insert into user(id) values(%d)", i);
			conn.connect("你的数据库服务器ip", 3306, "数据库用户名", "数据库登录密码", "testSql");
			conn.update(sql);
		}
		});

	thread t2([]() {
		for (int i = 0; i < 1250; i++) {
			Connection conn;
			char sql[1024] = { 0 };
			sprintf(sql, "insert into user(id) values(%d)", i);
			conn.connect("你的数据库服务器ip", 3306, "数据库用户名", "数据库登录密码", "testSql");
			conn.update(sql);
		}
		});

	thread t3([]() {
		for (int i = 0; i < 1250; i++) {
			Connection conn;
			char sql[1024] = { 0 };
			sprintf(sql, "insert into user(id) values(%d)", i);
			conn.connect("你的数据库服务器ip", 3306, "数据库用户名", "数据库登录密码", "testSql");
			conn.update(sql);
		}
		});

	thread t4([]() {
		for (int i = 0; i < 1250; i++) {
			Connection conn;
			char sql[1024] = { 0 };
			sprintf(sql, "insert into user(id) values(%d)", i);
			conn.connect("你的数据库服务器ip", 3306, "数据库用户名", "数据库登录密码", "testSql");
			conn.update(sql);
		}
		});

	t1.join();
	t2.join();
	t3.join();
	t4.join();

#endif


#if 0
	// 模拟四线程 模拟10000个连接量 不带连接池
	thread t1([]() {
		for (int i = 0; i < 2500; i++) {
			Connection conn;
			char sql[1024] = { 0 };
			sprintf(sql, "insert into user(id) values(%d)", i);
			conn.connect("你的数据库服务器ip", 3306, "数据库用户名", "数据库登录密码", "testSql");
			conn.update(sql);
		}
		});

	thread t2([]() {
		for (int i = 0; i < 2500; i++) {
			Connection conn;
			char sql[1024] = { 0 };
			sprintf(sql, "insert into user(id) values(%d)", i);
			conn.connect("你的数据库服务器ip", 3306, "数据库用户名", "数据库登录密码", "testSql");
			conn.update(sql);
		}
		});

	thread t3([]() {
		for (int i = 0; i < 2500; i++) {
			Connection conn;
			char sql[1024] = { 0 };
			sprintf(sql, "insert into user(id) values(%d)", i);
			conn.connect("你的数据库服务器ip", 3306, "数据库用户名", "数据库登录密码", "testSql");
			conn.update(sql);
		}
		});

	thread t4([]() {
		for (int i = 0; i < 2500; i++) {
			Connection conn;
			char sql[1024] = { 0 };
			sprintf(sql, "insert into user(id) values(%d)", i);
			conn.connect("你的数据库服务器ip", 3306, "数据库用户名", "数据库登录密码", "testSql");
			conn.update(sql);
		}
		});

	t1.join();
	t2.join();
	t3.join();
	t4.join();

#endif
	clock_t end = clock();
	cout << "sql语句执行耗费" << (end - begin) << "ms" << endl;
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值