1.
1 usingSystem;2 usingSystem.Collections;3 usingMySql.Data.MySqlClient;4 5 namespaceHelper6 {7 /// <summary>8 ///MySQL Connection pool9 /// </summary>Ten Public Static classMysqlconnpool One { A //private static string connstr = "server=localhost; User Id=root; Password=qwer1234;database=test; ";//Connection String - Private StaticArrayList Poolls =NewArrayList ();//Connection Pool - Private Static intMax = -;//maximum number of connection pools the - /// <summary> - ///Get Connection Object - /// </summary> + /// <param name= "ConnStr" >Database connection String</param> - /// <returns></returns> + Public StaticMysqlconnection Getconn (stringconnstr) A { at Lock(poolls) - { -Mysqlconnection Retconn =NULL;//return NULL when the hyper-thread pool size is limited - if(Poolls.count >0) - { -Retconn = (mysqlconnection) poolls[0];//gets the first in a pool inPoolls.removeat (0);//Remove from Pool - } to Else + { -Retconn =NewMysqlconnection (CONNSTR);//There is no connection in the connection pool, creating a the Retconn.open (); * } $ returnRetconn;Panax Notoginseng } - } the + /// <summary> A ///to close a connection or add to a connection pool the /// </summary> + /// <param name= "conn" ></param> - Public Static voidClose (mysqlconnection conn) $ { $ Lock(poolls) - { - if(Poolls.count < Max)//the connection pool retains only the maximum number of connections the { -POOLLS.ADD (conn);//The number of connection pools is less than the limit and the connection is added to the connection poolWuyi } the Else - { WuConn. Close ();//thread pool exceeded quantity limit, close connection - } About } $ } - } -}Connection Pool Code
2.
1 usingSystem;2 usingSYSTEM.WEB.MVC;3 usingSystem.Data;4 usingMySql.Data.MySqlClient;5 usingHelper;6 7 8 namespaceMVC4. Controllers9 {Ten Public classTestcontroller:controller One { A Private Static stringConnStr ="Server=localhost; User Id=root; Password=12345678;database=test;"; - Publicactionresult Index () - { theMysqlconnection conn =Mysqlconnpool.getconn (CONNSTR); -Mysqlcommand cmd =NewMysqlcommand ("Select * from Us_baseinfo", conn); -Mysqldatareader dr =cmd. ExecuteReader (); - if(Dr. Read ()) + { - } +Dr. Close ();//Close Mysqldatareader A Mysqlconnpool.close (conn); at returnView (); - } - } -}Connection Pool Usage
MySQL Connection pool