码海拾遗:基于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第一 ...
随机推荐
- iOS Reactivecocoa(RAC)知其所以然(源码分析,一篇足以)
前言 如今RAC大行其道,对其讲解的博客也多不胜数,稍微有点经验的估计也已经对这个爽到不要不要的框架运用自如了,真正沉下来研究其实现原理的估计也不在少数,这里仅仅是记录一下自己的分析理解,更是在写这篇 ...
- POJ-1751 Highways(最小生成树消边+输出边)
http://poj.org/problem?id=1751 Description The island nation of Flatopia is perfectly flat. Unfortun ...
- 17.3.15---C语言详解FILE文件操作
FILE 是 C语言文件结构定义, 打开文件和文件操作要用到这类结构.可以看成变量类型,用于变量声明.这个是一种数据结构类型,用来表示一个文件的相关信息,如果定义了一个文件指针,就用这个指针来指向某个 ...
- java调用IPFS去中心化体系
Maven pom.xml引入 <repositories> <repository> <id>jitpack.io</id> <url>h ...
- 吴裕雄--天生自然C语言开发:存储类
{ int mount; auto int month; } { register int miles; } #include <stdio.h> /* 函数声明 */ void func ...
- 微软不将《帝国时代》终极版上架Steam的原因到底是什么?
毋庸置疑的是,<帝国时代>绝对是一款经典游戏.作为一款RTS名作,在过去的20年时间中<帝国时代>销量超过2000万部.数以千万计的玩家都沉溺于这款游戏中,<帝国时代&g ...
- POJ 3617 Best Cow Line 字典序最小
#include<cstdio> #include<iostream> #include<algorithm> #include<queue> #inc ...
- id NSObject instanceType 区别
id 当不确定数组元素类型时,可以选择使用id NSObject和id都可以指向任何对象 NSObject使用时必须强转 instantceType 只能返回和方法所在类相同类型的对象 返回值类 ...
- laravel中用到的ServiceProvide
路由 全局限制 如果你希望路由参数可以总是遵循正则表达式,则可以使用 pattern 方法.你应该在 RouteServiceProvider 的 boot 方法里定义这些模式: 1 2 3 4 5 ...
- LeetCode No.79,80,81
No.79 Exist 单词搜索 题目 给定一个二维网格和一个单词,找出该单词是否存在于网格中. 单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中"相邻"单元格是那些水平相 ...