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 }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。