bitsCN.com
连接池为了解决频繁的创建、销毁所带来的系统开销。
简而言之,就是 自己先创建一定量的连接,然后在需要的时候取出一条连接使用。
当然如果你只有一个线程连接数据库,而且不是实时返回结果,那么你完全不必用连接池。
想一下网络大型游戏服务器,你就明白为什么需要连接池了。
自己敲代码写了一个简单的类,实现连接池,虽然没有mysql++那么强大,但是还是自己有收获。
Csqlpool.h 头文件实现如下:
#pragma once#include <WinSock2.h>#include <mysql.h>#include <list>#pragma comment( lib , "libmysql.lib" )using namespace std;class Csqlpool{public: ~Csqlpool(void); static Csqlpool *GetSqlPool(); bool IniSqlPool( const char *host , const char *name , const char *pwd , unsigned int port , unsigned int conMax ); //初始化连接池 bool SelectDB( MYSQL *sql, const char *DB); //选择数据库 MYSQL *GetConnect(); // 获取连接 void RelConnect(MYSQL *sql) ; // 释放连接 MYSQL_RES* GetQuery( MYSQL *sql , const char *query); //mysql操作 增删查改 void RelQuery(MYSQL_RES *res); //释放MYSQL_RES资源 bool Query(MYSQL *sql , const char *query); //增、删、改操作protected: Csqlpool(void);private: list<MYSQL *> m_sql_free; //空闲连接 static Csqlpool *pSqlPool; CRITICAL_SECTION m_session; //获取空闲线程};
Csqlpool.cpp 实现如下:
#include "StdAfx.h"#include "Csqlpool.h"Csqlpool *Csqlpool::pSqlPool = NULL;Csqlpool::Csqlpool(void){ InitializeCriticalSection( &m_session );}Csqlpool::~Csqlpool(void){ while ( m_sql_free.size() ) { mysql_close( m_sql_free.front() ); m_sql_free.pop_front(); } DeleteCriticalSection(&m_session);}Csqlpool* Csqlpool::GetSqlPool(){ if ( pSqlPool == NULL ) { return new Csqlpool; } return pSqlPool;}bool Csqlpool::IniSqlPool( const char *host ,const char *name , const char *pwd , unsigned int port , unsigned int conMax ) //初始化连接池{ int nsum = 0 ; for (unsigned int i = 0 ; i < conMax ;++i ) { MYSQL *pmysql; pmysql = mysql_init( (MYSQL*)NULL ); if ( pmysql != NULL ) { if ( mysql_real_connect( pmysql , host , name , pwd , NULL , 3306 , NULL , 0 ) ) { m_sql_free.push_back(pmysql); } else { if ( nsum++ == 100 ) { return false; } continue; } } continue; } return true;}bool Csqlpool::SelectDB( MYSQL *sql, const char *DB) //选择数据库{ if(mysql_select_db(sql , DB)) { return false; } return true;}MYSQL* Csqlpool::GetConnect() // 获取连接{ if ( m_sql_free.size() ) { EnterCriticalSection(&m_session); MYSQL *mysql = m_sql_free.front(); m_sql_free.pop_front(); LeaveCriticalSection(&m_session); return mysql; } else return NULL;}void Csqlpool::RelConnect(MYSQL *sql) // 释放连接{ EnterCriticalSection(&m_session); m_sql_free.push_back(sql); LeaveCriticalSection(&m_session);}MYSQL_RES* Csqlpool::GetQuery( MYSQL *sql , const char *query) //查询操作{ if ( mysql_query( sql , query ) == 0 ) { return mysql_store_result( sql ); } else return NULL;}void Csqlpool::RelQuery(MYSQL_RES *res) //mysql_res release{ mysql_free_result(res);}bool Csqlpool::Query(MYSQL *sql , const char *query) //增、删、改操作{ if ( mysql_query( sql , query ) ) { return false; } return true;}
testsqlpool.cpp 测试文件实现如下:
// testsqlpool.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include "Csqlpool.h"#include <iostream>using namespace std;Csqlpool *psql = Csqlpool::GetSqlPool();DWORD WINAPI ThreadProc( LPVOID lpParameter);int _tmain(int argc, _TCHAR* argv[]){ if(!psql->IniSqlPool("127.0.0.1" , "root" ,"123",3306,10)) { cout<<"连接错误"<<endl; } HANDLE phan[2] ; DWORD threadid[2]; int n1 = 0, n2 = 100;; phan[0] = CreateThread( NULL , 0 , ThreadProc , &n1 , 0 , &threadid[0] ); phan[1] = CreateThread( NULL , 0 , ThreadProc , &n2 , 0 , &threadid[1] ); WaitForMultipleObjects( 2 , phan , true , INFINITE ); CloseHandle(phan[0]); CloseHandle(phan[1]); return 0;}DWORD WINAPI ThreadProc( LPVOID lpParameter){ int index = *(int *)lpParameter ; int i = 1; MYSQL *sql = psql->GetConnect(); string stemp = "insert into actor( actor_id , first_name , last_name,last_update )values(/""; string strsql; char str[10]; if ( psql->SelectDB(sql , "sakila") ) { while ( i != 100 ) { sprintf( str , "%d" , i+index ); strsql = stemp ; strsql += str; strsql += "/",/"0/",/"0/",/"0/")"; if(!sql) return 0; if(!psql->Query( sql ,strsql.c_str() )) { cout<<"add false"<<endl; } ++i; } psql->RelConnect(sql); } return 0;}bitsCN.com

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

The steps to build a MySQL database include: 1. Create a database and table, 2. Insert data, and 3. Conduct queries. First, use the CREATEDATABASE and CREATETABLE statements to create the database and table, then use the INSERTINTO statement to insert the data, and finally use the SELECT statement to query the data.

MySQL is suitable for beginners because it is easy to use and powerful. 1.MySQL is a relational database, and uses SQL for CRUD operations. 2. It is simple to install and requires the root user password to be configured. 3. Use INSERT, UPDATE, DELETE, and SELECT to perform data operations. 4. ORDERBY, WHERE and JOIN can be used for complex queries. 5. Debugging requires checking the syntax and use EXPLAIN to analyze the query. 6. Optimization suggestions include using indexes, choosing the right data type and good programming habits.

MySQL is suitable for beginners because: 1) easy to install and configure, 2) rich learning resources, 3) intuitive SQL syntax, 4) powerful tool support. Nevertheless, beginners need to overcome challenges such as database design, query optimization, security management, and data backup.

Yes,SQLisaprogramminglanguagespecializedfordatamanagement.1)It'sdeclarative,focusingonwhattoachieveratherthanhow.2)SQLisessentialforquerying,inserting,updating,anddeletingdatainrelationaldatabases.3)Whileuser-friendly,itrequiresoptimizationtoavoidper

ACID attributes include atomicity, consistency, isolation and durability, and are the cornerstone of database design. 1. Atomicity ensures that the transaction is either completely successful or completely failed. 2. Consistency ensures that the database remains consistent before and after a transaction. 3. Isolation ensures that transactions do not interfere with each other. 4. Persistence ensures that data is permanently saved after transaction submission.

MySQL is not only a database management system (DBMS) but also closely related to programming languages. 1) As a DBMS, MySQL is used to store, organize and retrieve data, and optimizing indexes can improve query performance. 2) Combining SQL with programming languages, embedded in Python, using ORM tools such as SQLAlchemy can simplify operations. 3) Performance optimization includes indexing, querying, caching, library and table division and transaction management.

MySQL uses SQL commands to manage data. 1. Basic commands include SELECT, INSERT, UPDATE and DELETE. 2. Advanced usage involves JOIN, subquery and aggregate functions. 3. Common errors include syntax, logic and performance issues. 4. Optimization tips include using indexes, avoiding SELECT* and using LIMIT.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version
Useful JavaScript development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version
Recommended: Win version, supports code prompts!

Zend Studio 13.0.1
Powerful PHP integrated development environment