Code sea supplements: MySQL-based connector/c++ MySQL operation (connection pooling)

Source: Internet
Author: User
Tags connection pooling

1. mysql Installation and simple setup

(1) Installation: Under the OSX system, you can use the universal "Brew Install" command to install: Brew isntall mysql (default to install the latest version of MySQL)

(2) Start: Brew services start MySQL

(3) Change Password: Update user Set authentication_string = password (' password '), password_expired = ' N ', password_last_changed = Now () WH ere user = ' root ';

- flush privileges; (Let the modified password take effect)

(4) Allow remote access: Update mysql.user set host = '% ' where user = ' root ';

2. MySQL connector/c++ Installation

(1) Download: MySQL connector/c++ source can be downloaded from here

(2) Installation: After decompression, the "include" directory files are copied to the "/usr/local/include" directory, "Lib" Directory files are copied into the "/usr/local/lib" directory can be

3. Sample code (lazy model based on singleton mode)

CConnPool.h

/* * CConnPool.h * * Created On:mar, 2018 * author:root * * #ifndef src_cconnpool_h_#define SRC_CCONNPOOL_H_#INCL Ude <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 ();p rivate: Cconnpool (); Connection*createconnection (); Create a connection void initconnection (int iinitialsize); Initialize database connection pool void Destoryconnection (Connection *conn); Destroy database Connection object void Destoryconnpool (); Destroys database connection pool cconnpool (string url, string user, string password, int maxSize); Construction Method PrivaTe:int cursize; The number of database connections currently established int maxSize; The maximum number of database connections defined in the connection pool string user;string password;string url;list<connection*> connlist; The container queue of the connection pool STL list bidirectional linked list pthread_mutex_t lock; Thread lock static Cconnpool *connpool;driver*driver;}; #endif/* Src_cconnpool_h_ */

CConnPool.cpp

/* * CConnPool.cpp * * Created On:mar, 2018 * author:root * * #include <stdexcept> #include <exception&gt ; #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 = PA Ssword;this->url = Url;try{this->driver = Sql::mysql::get_driver_instance ();} catch (Sql::sqlexception &e) {perror ("drive connection error; \ n");} catch (Std::runtime_error &e) {perror ("Run error \ n");} This->initconnection (MAXSIZE/2);p thread_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 ("drive connection error; \ n");} catch (Std::runtime_error &e) {perror ("Run error \ n");} This->initconnection (MAXSIZE/2);p thread_mutex_init (&lock, NULL);} Cconnpool *cconnpool::getinstance () {if (Connpool = = NULL) Connpool = new Cconnpool ("tcp://127.0.0.1:3306", "Root", " 123456 ","); return connpool;} void cconnpool::initconnection (int num) {Connection *conn;pthread_mutex_lock (&lock); for (int i = 0; i < num; ++i) {C Onn = CreateConnection (); if (conn) {connlist.push_back (conn); ++cursize;} Else{perror ("Error creating Connection");}} Pthread_mutex_unlock (&lock);} Connection *cconnpool::createconnection () {Connection *conn;try{conn = driver->connect (url, user, password);// Establish connection 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);p Thread_mutex_unlock (&lock);}} Cconnpool::~cconnpool () {This->destoryconnpool ();} void Cconnpool::D estoryconnpool () {list<connection *>::iterator iter;pthread_mutex_lock (&lock); for (iter = Connlist.begin (); Iter! = Connlist.end (); ++iter) this->destoryconnection (*iter), cursize = 0;connlist.clear ();p thread_mutex_unlock (&lock);} void Cconnpool::D estoryconnection (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;}

  

Code sea supplements: MySQL-based connector/c++ MySQL operation (connection pooling)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.