码海拾遗:基于MySQL Connector/C++的MySQL操作(连接池)
1、MySQL安装及简单设置
(1)安装:在OSX系统下,可以使用万能的“brew install”命令来进行安装:brew isntall mysql(默认安装最新版的MySQL)
(2)启动:brew services start mysql
(3)修改密码:update user set authentication_string = password('password'), password_expired = 'N', password_last_changed = now() where user = 'root';
-->flush privileges;(让修改后的密码生效)
(4)允许远程访问:update mysql.user set host = '%' where user = 'root';
2、MySQL Connector/C++安装
(1)下载:MySQL Connector/C++源码可以从这里下载
(2)安装:解压后将“include”目录下的文件复制到“/usr/local/include”目录下,“lib”目录下的文件复制到“/usr/local/lib”目录下即可
3、示例代码(基于单例模式的懒汉模型)
CConnPool.h
/*
* CConnPool.h
*
* Created on: Mar 15, 2018
* Author: root
*/ #ifndef SRC_CCONNPOOL_H_
#define SRC_CCONNPOOL_H_ #include <list>
#include <string> #include <pthread.h> #include <mysql_connection.h>
#include <mysql_driver.h>
#include <cppconn/exception.h>
#include <cppconn/driver.h>
#include <cppconn/connection.h>
#include <cppconn/resultset.h>
#include <cppconn/prepared_statement.h>
#include <cppconn/statement.h> using namespace sql;
using namespace std; class CConnPool {
public:
~CConnPool();
void InitConnpool(string url, string user, string password, int maxSize);
Connection* GetConnection();
void ReleaseConnection(Connection* conn);
static CConnPool *GetInstance(); private:
CConnPool();
Connection*CreateConnection(); //创建一个连接
void InitConnection(int iInitialSize); //初始化数据库连接池
void DestoryConnection(Connection *conn); //销毁数据库连接对象
void DestoryConnPool(); //销毁数据库连接池
CConnPool(string url, string user, string password, int maxSize); //构造方法 private:
int curSize; //当前已建立的数据库连接数量
int maxSize; //连接池中定义的最大数据库连接数
string user;
string password;
string url;
list<Connection*> connList; //连接池的容器队列 STL list 双向链表
pthread_mutex_t lock; //线程锁
static CConnPool *connPool;
Driver*driver;
}; #endif /* SRC_CCONNPOOL_H_ */
CConnPool.cpp
/*
* CConnPool.cpp
*
* Created on: Mar 15, 2018
* Author: root
*/ #include <stdexcept>
#include <exception>
#include <cstdio> #include "CConnPool.h" CConnPool *CConnPool::connPool = NULL;
//CConnPool* CConnPool::connPool = new CConnPool(); CConnPool::CConnPool()
{
// TODO Auto-generated constructor stub
} void CConnPool::InitConnpool(string url, string user, string password,
int maxSize)
{
this->maxSize = maxSize;
this->curSize = 0;
this->user = user;
this->password = password;
this->url = url;
try
{
this->driver = sql::mysql::get_driver_instance();
}
catch (sql::SQLException &e)
{
perror("驱动连接出错;\n");
}
catch (std::runtime_error &e)
{
perror("运行出错了\n");
}
this->InitConnection(maxSize / 2);
pthread_mutex_init(&lock, NULL);
} CConnPool::CConnPool(string url, string user, string password, int maxSize)
{
this->maxSize = maxSize;
this->curSize = 0;
this->user = user;
this->password = password;
this->url = url;
try
{
this->driver = sql::mysql::get_driver_instance();
}
catch (sql::SQLException &e)
{
perror("驱动连接出错;\n");
}
catch (std::runtime_error &e)
{
perror("运行出错了\n");
}
this->InitConnection(maxSize / 2);
pthread_mutex_init(&lock, NULL);
} CConnPool *CConnPool::GetInstance()
{
if (connPool == NULL)
connPool = new CConnPool("tcp://127.0.0.1:3306", "root", "123456",
10);
return connPool;
} void CConnPool::InitConnection(int num)
{
Connection *conn;
pthread_mutex_lock(&lock);
for (int i = 0; i < num; ++i)
{
conn = CreateConnection();
if (conn)
{
connList.push_back(conn);
++curSize;
}
else
{
perror("创建CONNECTION出错");
}
}
pthread_mutex_unlock(&lock);
} Connection *CConnPool::CreateConnection()
{
Connection *conn;
try
{
conn = driver->connect(url, user, password); //建立连接
return conn;
}
catch (sql::SQLException &e)
{
perror(e.what());
return NULL;
}
catch (std::runtime_error &e)
{
perror(e.what());
return NULL;
}
} Connection *CConnPool::GetConnection()
{
Connection *conn;
pthread_mutex_lock(&lock); if (connList.size() > 0)
{
conn = connList.front();
connList.pop_front();
if (conn->isClosed())
{
delete conn;
conn = CreateConnection();
}
if (conn == NULL)
--curSize;
pthread_mutex_unlock(&lock);
return conn;
}
else
{
if (curSize < maxSize)
{
conn = CreateConnection();
if (conn)
{
++curSize;
pthread_mutex_unlock(&lock);
return conn;
}
else
{
pthread_mutex_unlock(&lock);
return NULL;
}
}
else
{
pthread_mutex_unlock(&lock);
return NULL;
}
}
} void CConnPool::ReleaseConnection(Connection *conn)
{
if (conn)
{
pthread_mutex_lock(&lock);
connList.push_back(conn);
pthread_mutex_unlock(&lock);
}
} CConnPool::~CConnPool()
{
this->DestoryConnPool();
} void CConnPool::DestoryConnPool()
{
list<Connection *>::iterator iter;
pthread_mutex_lock(&lock);
for (iter = connList.begin(); iter != connList.end(); ++iter)
this->DestoryConnection(*iter);
curSize = 0;
connList.clear();
pthread_mutex_unlock(&lock);
} void CConnPool::DestoryConnection(Connection *conn)
{
if (conn)
{
try
{
conn->close();
}
catch (sql::SQLException &e)
{
perror(e.what());
}
catch (std::exception &e)
{
perror(e.what());
}
delete conn;
}
}
main.cpp
#include <iostream>
#include <string> #include "CConnPool.h" using std::cout;
using std::endl;
using std::string; CConnPool *connpool = CConnPool::GetInstance(); int main(int argc, char *argv[])
{
Connection *conn;
Statement *state;
ResultSet *result; conn = connpool->GetConnection();
state = conn->createStatement();
state->execute("use mysql"); result = state->executeQuery("select host,user from user");
while (result->next())
{
try
{
string user = result->getString("user");
string host = result->getString("host");
cout << user << "@" << host << endl;
}
catch (sql::SQLException &e)
{
cout << e.what() << endl;
}
} delete result;
delete state;
connpool->ReleaseConnection(conn); getchar();
return 0;
}
码海拾遗:基于MySQL Connector/C++的MySQL操作(连接池)的更多相关文章
- 基于Python3实现的各类数据库连接和连接池
基于Python3的各类数据库连接和连接池, 支持数据库有: Mysql(MariaDB), Oracle, PostgreSQL(GreenPlum), Vertica, Redis, MongoD ...
- MySql 8小时解决方案:proxool连接池
最近做的项目用的mysql数据库,前天挂在服务器上,昨天早晨上班一来,同事就说API数据接口访问不了了,我马上mstsc登陆服务器看,报错了.马上重启tomcat,结果还能正常运行,当时没管,今天过来 ...
- 【Mysql】SpringBoot阿里Druid数据源连接池配置
一.pom.xml添加 <!-- 配置数据库连接池 --> <dependency> <groupId>com.alibaba</groupId> &l ...
- 码海拾遗:strcpy()、strncpy()和strcpy_s()区别
1.strcpy() 原型:char *strcpy(char *dst,const char *src) 功能:将以src为首地址的字符串复制到以dst为首地址的字符串,包括'\0'结束符,返回ds ...
- 码海拾遗:Linux常用命令(一)
一.Linux系统安装 系统安装可以分两类:实体机安装Linux,虚拟机(常用虚拟机软件有两种:VMware和VirtualBox)安装Linux. 安装过程网上有很多教程,这里就不赘述了. 二.常用 ...
- 码海拾遗:简单Socket(TCP)类实现
最近刚开始啃Unix网络编程(卷1:套接字联网API),为加深TCP连接的建立和终止的理解与记忆,记下本文,方便以后翻看. 同时留下的还有简单的Socket(TCP)类: mySocket.h #pr ...
- 码海拾遗:Linux多线程mutex锁
多线程计数,每个线程累加10个数. 实现: #include <stdio.h> #include <stdlib.h> #include <string.h> # ...
- 码海拾遗:简述C++(一)
C++是Bjarne Stroustrup博士于1982年,在C语言的基础上引入并扩充了面向对象的概念后发明的一种新的程序语言.就与C语言的渊源而言,C++可以说是C语言的超集,它兼容C的一切(可能是 ...
- 码海拾遗:strstr()、strcmp()和strcpy()实现
1.strstr()实现 原型:char * strstr(const char * str1, const char * str2) 说明:判断str2是否为str1的子串,如果是则返回str2第一 ...
随机推荐
- GetCharWidth32
#include <windows.h> #include<stdio.h> // 窗口函数的函数原形 LRESULT CALLBACK MainWndProc(HWND, U ...
- 描述符(\_\_get\_\_和\_\_set\_\_和\_\_delete\_\_)
描述符(__get__和__set__和__delete__) 一.描述符 描述符是什么:描述符本质就是一个新式类,在这个新式类中,至少实现了__get__(),set(),delete()中的一个, ...
- GCC与gcc,g++区别
看的Linux公社的一篇文章,觉得不错,内容复制过来了. 其实在这之前,我一直以为gcc和g++是一个东西,只是有两个不同的名字而已,今天在linux下编译一个c代码时出现了错误才找了一下gcc和g+ ...
- linux_cat命令
cat 命令可以用来显示文本文件的内容(类似于 DOS 下的 type 命令),也可以把几个文件内容附加到另一个文件中,即连接合并文件. 关于此命令,有人认为写 cat 命令的人是因为喜欢猫,因此给此 ...
- D. Almost All Divisors
We guessed some integer number xx. You are given a list of almost all its divisors. Almost all means ...
- day32-socketserver
#socketserver 是在socket基础上进行了封装,它让server可以实时跟多个client进行通信. #thread线程:一个程序有一个线程,一个线程是调度cpu的最小单位.程序运行才产 ...
- JAVA单例模式的几种写法
/** * 单例模式懒汉式(双重检锁线程安全.JDK1.5之后) */ public class Singleton { private static volatile Singleton singl ...
- 吴裕雄--天生自然python学习笔记:pandas模块读取 Data Frame 数据
读取行数据 读取一个列数据的语法为: 例如,读取所有学生自然科目的成绩 : import pandas as pd datas = [[65,92,78,83,70], [90,72,76,93,56 ...
- resent|aspiration|deficiency|diagnosed|distract|emphasize
VERB 怨恨;憎恶;愤恨If you resent someone or something, you feel bitter and angry about them. She resents h ...
- [LC] 674. Longest Continuous Increasing Subsequence
Given an unsorted array of integers, find the length of longest continuous increasing subsequence (s ...