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操作(连接池)的更多相关文章

  1. 基于Python3实现的各类数据库连接和连接池

    基于Python3的各类数据库连接和连接池, 支持数据库有: Mysql(MariaDB), Oracle, PostgreSQL(GreenPlum), Vertica, Redis, MongoD ...

  2. MySql 8小时解决方案:proxool连接池

    最近做的项目用的mysql数据库,前天挂在服务器上,昨天早晨上班一来,同事就说API数据接口访问不了了,我马上mstsc登陆服务器看,报错了.马上重启tomcat,结果还能正常运行,当时没管,今天过来 ...

  3. 【Mysql】SpringBoot阿里Druid数据源连接池配置

    一.pom.xml添加 <!-- 配置数据库连接池 --> <dependency> <groupId>com.alibaba</groupId> &l ...

  4. 码海拾遗:strcpy()、strncpy()和strcpy_s()区别

    1.strcpy() 原型:char *strcpy(char *dst,const char *src) 功能:将以src为首地址的字符串复制到以dst为首地址的字符串,包括'\0'结束符,返回ds ...

  5. 码海拾遗:Linux常用命令(一)

    一.Linux系统安装 系统安装可以分两类:实体机安装Linux,虚拟机(常用虚拟机软件有两种:VMware和VirtualBox)安装Linux. 安装过程网上有很多教程,这里就不赘述了. 二.常用 ...

  6. 码海拾遗:简单Socket(TCP)类实现

    最近刚开始啃Unix网络编程(卷1:套接字联网API),为加深TCP连接的建立和终止的理解与记忆,记下本文,方便以后翻看. 同时留下的还有简单的Socket(TCP)类: mySocket.h #pr ...

  7. 码海拾遗:Linux多线程mutex锁

    多线程计数,每个线程累加10个数. 实现: #include <stdio.h> #include <stdlib.h> #include <string.h> # ...

  8. 码海拾遗:简述C++(一)

    C++是Bjarne Stroustrup博士于1982年,在C语言的基础上引入并扩充了面向对象的概念后发明的一种新的程序语言.就与C语言的渊源而言,C++可以说是C语言的超集,它兼容C的一切(可能是 ...

  9. 码海拾遗:strstr()、strcmp()和strcpy()实现

    1.strstr()实现 原型:char * strstr(const char * str1, const char * str2) 说明:判断str2是否为str1的子串,如果是则返回str2第一 ...

随机推荐

  1. python——logging模块

    简介: 日志是一种可以追踪某些软件运行时所发生事件的方法.软件开发人员可以向他们的代码中调用日志记录相关的方法来表明发生了某些事情.不同的事件,被区分在不同的等级中,故通过log分析,可以很轻易地分析 ...

  2. Linux-proc文件系统介绍

    1.操作系统级别的调试 (1).简单程序单步调试 (2).复杂程序printf打印信息调试 (3).框架体系日志记录信息调试 (4).内核调试的困境 2.proc虚拟文件系统的工作原理 (1).Lin ...

  3. 《C程序设计(第四版)》小记

    我看的这本书很经典,它是谭浩强写的,也就是广为流传的“C语言红皮书”.在网上看了很多帖子,生活中也问过一些朋友,大多数人是不认可这本书的.很多人都说这本书很烂,看不懂,然后去“追逐”国外的一些教材.其 ...

  4. Rnotebook中用python画图

    如果notebook需要转化为pdf, 能想到办法是保存图片文件,嵌入mardown语法中. 但是如果在html中显示, 可以考虑下面思虑, 比较取巧. ``` {python, engine.pat ...

  5. iTOP4412开发板-使用buildroot搭建最简单的linux

    本文档介绍的是使用buildroot搭建最简单的linux文件系统,Buildroot是Linux平台上一个构建嵌入式Linux系统的框架.整个Buildroot是由Makefile脚本和Kconfi ...

  6. 35)PHP,关于PHP和html

    (1)其实无论是CSS还是js,又或者是html,都是可以随意的载入到我们的php文件中,其实这些文件就是一个外来的引入文件,所以,根本没有什么神奇的, 你要是想把php的结果有调理的展示,那么就直接 ...

  7. kubernetes flannel 网卡绑定错误,故障排查

    kubernetes 新加了个node,状态Ready,但调度过去的任务,都执行异常 查看异常节点日志 `Error adding net work: open run/flannel/subnet. ...

  8. 系统学习Javaweb9----BootStrap1

    学习内容: 1.BootStrap的简述 2.BootStrap环境搭建 3.BootStrap环境搭建-基本模板创建 4.BootStrap环境搭建-基本模板讲解 5.BootStrap布局容器 6 ...

  9. Django+Ajax+Mysql实现数据库数据的展示

    最近老师让搞一个系统,仅仅展示一下数据库的数据 在做海底捞时,是交接的师兄的项目,用的语言是java,框架是SSM(Spring.SpringMVC.MyBatis),这次我准备用Python写,前端 ...

  10. python后端面试第八部分:制作简历和如何面试--长期维护

    ###############     就业指导    ################ 这里面有套路,你懂了这个套路,你会找到更好的工作,你会更快的找到工作, ,如何制作简历,五颗星 ,如何投递简历 ...