首页 > 代码库 > MySQL连接池
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 MySQLConnPool11 {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;//超出线程池大小限制时返回null26 if (poolLs.Count > 0)27 {28 retConn = (MySqlConnection)poolLs[0];//获取池中第一个29 poolLs.RemoveAt(0);//从池中移除30 }31 else32 {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 else53 {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 : Controller11 {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();//关闭MySqlDataReader22 MySQLConnPool.Close(conn);23 return View();24 }25 }26 }
MySQL连接池
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。