C++动态链接MySQL库

C++链接MySQL库

库安装目录
在这里插入图片描述
在这里插入图片描述
CMakeList

cmake_minimum_required(VERSION 3.22)
project(MySQLConnectionPool)

include_directories(/usr/include/mysql)	#安装库路径

set(CMAKE_CXX_STANDARD 17)

add_executable(MySQLConnectionPool main.cpp)


target_link_libraries(MySQLConnectionPool mysqlclient)

测试代码

//1.test.c
#include<cstdio>
#include "mysql/mysql.h"

int main() {
  MYSQL * mysql = NULL;
  if ((mysql = mysql_init(NULL)) == NULL) {
	fprintf(stderr, "error in mysql_init\n");
	exit(1);
  }

  mysql = mysql_real_connect(mysql, "localhost", "root", "lhh123456", "Test", 3306, 0, 0);

  if (!mysql) {
	fprintf(stderr, "connection failed!\n");
	exit(1);
  }

  printf("Success!\n");
  return 0;
}

在这里插入图片描述
不使用连接池
在这里插入图片描述
使用连接池
在这里插入图片描述

一定注意使用show variables like "max_connections";查看MySQL最大连接数,连接池最大连接不能超过这个数,使用set GLOBAL max_connections=1000;可以修改最大连接数

void test(int i) {
  char sql[512]{0};
  Connection conn;
  std::this_thread::sleep_for(std::chrono::milliseconds(2));
  sprintf(sql, "insert into Info(ID,UserName,IDCard,Passwd)values(%d,'%s','%s','%s');",
		  i, "zhangsan", std::to_string(i).c_str(), "123456");
  conn.connect("127.0.0.1", 3306, "root", "lhh123456", "Test");
  conn.update(sql);
}
void test1(int i) {
  char sql[512]{0};
  ConnectionPool *pool = ConnectionPool::getConnectionPool();
  std::shared_ptr<Connection> sp = pool->getConnection();
  sprintf(sql, "insert into Info(ID,UserName,IDCard,Passwd)values(%d,'%s','%s','%s');",
		  i, "zhangsan", std::to_string(i).c_str(), "123456");
  sp->update(sql);
}
posted @ 2022-11-15 20:48  DaoDao777999  阅读(72)  评论(0编辑  收藏  举报