Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

用unordered_map来存,加上共享指针,构造函数初始化 #5

Open
yuanlongdong opened this issue Jun 18, 2024 · 0 comments
Open

Comments

@yuanlongdong
Copy link

`#ifndef MYSQLPOOL_H
#define MYSQLPOOL_H
#include
#include<mysql.h>
#include
#include<unordered_map>
#include
#include
#include
#include
#include
#include

using namespace std;

class MysqlPool
{
public:
~MysqlPool();
unordered_map<string, vector<const char*>>executeSql(const char* sql, vector& columns);
static shared_ptr getMysqlPoolObject();
void setParameter(const char* _mysqlhost,
const char* _mysqluser,
const char* _mysqlpwd,
const char* _databasename,
unsigned int _port = 0,
const char* _socket = NULL,
unsigned long _client_flag = 0,
unsigned int MAX_CONNECT = 50);
unsigned int connect_count; //目前连接池的连接对象数量
private:
MysqlPool();
MYSQL* createOneConnect(); //创建一个新的连接对象
MYSQL* getOneConnect(); //获取一个连接对象
void close(MYSQL* con); //关闭连接对象
bool isEmpty(); //连接池队列池是否为空
MYSQL* poolFront(); //连接池队列的队头
unsigned int poolSize(); //获取连接池的大小
void poolPop(); //弹出连接池队列的队头
private:
queue<MYSQL*> mysqlPool; //连接池队列
const char* _mysqlhost; //mysql主机地址
const char* _mysqluser; //mysql用户名
const char* _mysqlpwd; //mysql密码
const char* _databasename; //要使用的mysql数据库名字
unsigned int _port; //mysql端口
const char* _socket; //可以设置成Socket or Pipeline,通常设置为NULL
unsigned long _client_flag; //设置为0
unsigned int MAX_CONNECT; //同时允许最大连接对象数量

static mutex objectlock;                 //对象锁
static mutex poollock;                   //连接池锁
static shared_ptr<MysqlPool> mysqlpool_object;           //类的对象

};
#endif // !MYSQLPOOL_H

#include "MysqlPool.h"

shared_ptr MysqlPool::mysqlpool_object = NULL;
mutex MysqlPool::objectlock;
mutex MysqlPool::poollock;

MysqlPool::MysqlPool() {
//初始化数据库
if (0 == mysql_library_init(0, NULL, NULL))
std::cout << "mysql_library_init()succeed" << std::endl;
else {
std::cout << "mysql_library_init()failed" << std::endl;
}
}

MysqlPool::~MysqlPool()
{
while (poolSize() != 0) {
mysql_close(poolFront());
poolPop();
connect_count--;
}
mysql_library_end();
}

unordered_map<string, vector<const char*>> MysqlPool::executeSql(const char* sql, vector& columns) {
MYSQL* conn = getOneConnect();
if (mysql_query(conn, "SET NAMES GBK")) {
std::cout << "Failed to set character set: " << mysql_error(conn) << std::endl;
exit(1);
}
unordered_map<string, vector<const char*>> results;
if (conn) {
if (mysql_query(conn, sql) == 0) {
MYSQL_RES* res = mysql_store_result(conn);
if (res) {
MYSQL_FIELD* field;
while ((field = mysql_fetch_field(res))) {
columns.push_back(field->name);
results[field->name] = vector<const char*>();
}
MYSQL_ROW row;
while ((row = mysql_fetch_row(res))) {
unsigned int i = 0;
for (const string& col : columns) {
results[col].push_back(row[i++]);
}
}
mysql_free_result(res);
}
else {
if (mysql_field_count(conn) != 0)
std::cerr << "MySQL error: " << mysql_error(conn) << std::endl;
}
}
else {
std::cerr << "MySQL query error: " << mysql_error(conn) << std::endl;
}
close(conn);
}
else {
std::cerr << "Failed to get MySQL connection." << std::endl;
}
return results;
}

shared_ptr MysqlPool::getMysqlPoolObject()
{
if (mysqlpool_object == NULL) {
objectlock.lock();
if (mysqlpool_object == NULL) {
shared_ptr ptr1(new MysqlPool());
mysqlpool_object = ptr1;
//mysqlpool_object = new MysqlPool();
}
objectlock.unlock();
}
return mysqlpool_object;
}

void MysqlPool::setParameter(const char* mysqlhost,
const char* mysqluser,
const char* mysqlpwd,
const char* databasename,
unsigned int port,
const char* socket,
unsigned long client_flag,
unsigned int max_connect) {
_mysqlhost = mysqlhost;
_mysqluser = mysqluser;
_mysqlpwd = mysqlpwd;
_databasename = databasename;
_port = port;
_socket = socket;
_client_flag = client_flag;
MAX_CONNECT = max_connect;

}

MYSQL* MysqlPool::createOneConnect()
{
MYSQL* conn = NULL;
conn = mysql_init(conn);

if (conn != NULL) {
	if (mysql_real_connect(conn,
		_mysqlhost,
		_mysqluser,
		_mysqlpwd,
		_databasename,
		_port,
		_socket,
		_client_flag)) {
		connect_count++;
		return conn;
	}
	else {
		std::cout << mysql_error(conn) << std::endl;
		return NULL;
	}
}
else {
	std::cerr << "init failed" << std::endl;
	return NULL;
}

}

MYSQL* MysqlPool::getOneConnect()
{
poollock.lock();
MYSQL* conn = NULL;
if (!isEmpty()) {
while (!isEmpty() && mysql_ping(poolFront())) {
mysql_close(poolFront());
poolPop();
connect_count--;
}
if (!isEmpty()) {
conn = poolFront();
poolPop();
}
else {
if (connect_count < MAX_CONNECT)
conn = createOneConnect();
else
std::cerr << "the number of mysql connections is too much!" << std::endl;
}
}
else {
if (connect_count < MAX_CONNECT)
conn = createOneConnect();
else
std::cerr << "the number of mysql connections is too much!" << std::endl;
}
poollock.unlock();
return conn;
}

void MysqlPool::close(MYSQL* con)
{
if (con != NULL) {
poollock.lock();
mysqlPool.push(con);
poollock.unlock();
}
}

bool MysqlPool::isEmpty()
{
return mysqlPool.empty();
}

MYSQL* MysqlPool::poolFront()
{
return mysqlPool.front();
}

unsigned int MysqlPool::poolSize()
{
return mysqlPool.size();
}

void MysqlPool::poolPop()
{
mysqlPool.pop();
}

#include"MysqlPool.h"

int main() {
shared_ptr mysql = MysqlPool::getMysqlPoolObject();
mysql->setParameter("localhost", "root", "051111", "lunwen", 3306, NULL, 0, 50);
vector columns;
unordered_map<string, vector<const char*> > m = mysql->executeSql("SELECT * FROM users",columns);
for (unordered_map<string, vector<const char*> >::iterator it = m.begin(); it != m.end(); ++it) {
cout << it->first <<":"<<endl;
string key1 = it->first;
int len = it->second.size();
for (int i = 0;i < len;i++)
{
cout << m[key1][i]<<" ";
}
cout<<endl;
}

cout << "当前连接数:" << mysql->connect_count << endl;




return 0;

}

下面是是效果:
image
`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant