MySQL连接池

 

1.

 1 using System;
 2 using System.Collections;
 3 using MySql.Data.MySqlClient;
 4 
 5 namespace Helper
 6 {
 7     /// <summary>
 8     /// MySQL连接池
 9     /// </summary>
10     public static class MySQLConnPool
11     {
12         //private static string connStr = "server=localhost;User ID=root;Password=qwer1234;database=test;";//连接字符串
13         private static ArrayList poolLs = new ArrayList();//连接池
14         private static int max = 20;//连接池最大数量
15 
16         /// <summary>
17         /// 获取连接对象
18         /// </summary>
19         /// <param name="connStr">数据库连接字符串</param>
20         /// <returns></returns>
21         public static MySqlConnection GetConn(string connStr)
22         {
23             lock (poolLs)
24             {
25                 MySqlConnection retConn = null;//超出线程池大小限制时返回null
26                 if (poolLs.Count > 0)
27                 {
28                     retConn = (MySqlConnection)poolLs[0];//获取池中第一个
29                     poolLs.RemoveAt(0);//从池中移除
30                 }
31                 else
32                 {
33                     retConn = new MySqlConnection(connStr);//连接池中没有连接,创建一个
34                     retConn.Open();
35                 }
36                 return retConn;
37             }
38         }
39 
40         /// <summary>
41         /// 关闭连接或添加到连接池
42         /// </summary>
43         /// <param name="conn"></param>
44         public static void Close(MySqlConnection conn)
45         {
46             lock (poolLs)
47             {
48                 if (poolLs.Count < max)//连接池只保留最大数量的连接
49                 {
50                     poolLs.Add(conn);//连接池数量小于限制,将连接添加到连接池
51                 }
52                 else
53                 {
54                     conn.Close();//线程池超出数量限制,关闭连接
55                 }
56             }
57         }
58     }
59 }
连接池代码

2.

 1 using System;
 2 using System.Web.Mvc;
 3 using System.Data;
 4 using MySql.Data.MySqlClient;
 5 using Helper;
 6 
 7 
 8 namespace MVC4.Controllers
 9 {
10     public class testController : Controller
11     {
12         private static string connStr = "server=localhost;User ID=root;Password=12345678;database=test;";
13         public ActionResult Index()
14         {
15             MySqlConnection conn = MySQLConnPool.GetConn(connStr);
16             MySqlCommand cmd = new MySqlCommand("Select * from us_BaseInfo", conn);
17             MySqlDataReader dr = cmd.ExecuteReader();
18             if (dr.Read())
19             {
20             }
21             dr.Close();//关闭MySqlDataReader
22             MySQLConnPool.Close(conn);
23             return View();
24         }
25     }
26 }
连接池使用

 

posted @ 2014-12-17 15:52  灰色雨逸  阅读(358)  评论(0编辑  收藏  举报