C#连接池

查阅了一天的资料来学习MySql数据库连接池,终于在一篇博文上找到了,自己也整理了一下,希望对大家有用处

1. 建立连接池

复制代码
  1 using MySql.Data.MySqlClient;
  2 using System;
  3 using System.Collections;
  4 using System.Collections.Generic;
  5 using System.Linq;
  6 using System.Text;
  7 using System.Threading.Tasks;
  8 
  9 namespace LianJieChiTest
 10 {
 11     public class ConnectionPool
 12     {
 13         private static ConnectionPool cpool = null;//池管理对象
 14         private static Object objlock = typeof(ConnectionPool);//池管理对象实例
 15         private int size = 1;//池中连接数
 16         private int useCount = 0;//已经使用的连接数
 17         private ArrayList pool = null;//连接保存的集合
 18         private String ConnectionStr = "";//连接字符串
 19 
 20         public ConnectionPool()
 21         {
 22             //数据库连接字符串
 23             ConnectionStr = "server=localhost;User ID=root;Password=123456;database=test;";
 24             //创建可用连接的集合
 25             pool = new ArrayList();
 26         }
 27 
 28         #region 创建获取连接池对象
 29         public static ConnectionPool getPool()
 30         {
 31             lock (objlock)
 32             {
 33                 if (cpool == null)
 34                 {
 35                     cpool = new ConnectionPool();
 36                 }
 37                 return cpool;
 38             }
 39         }
 40         #endregion
 41 
 42         #region 获取池中的连接
 43         public MySqlConnection getConnection()
 44         {
 45             lock (pool)
 46             {
 47                 MySqlConnection tmp = null;
 48                 //可用连接数量大于0
 49                 if (pool.Count > 0)
 50                 {
 51                     //取第一个可用连接
 52                     tmp = (MySqlConnection)pool[0];
 53                     //在可用连接中移除此链接
 54                     pool.RemoveAt(0);
 55                     //不成功
 56                     if (!isUserful(tmp))
 57                     {
 58                         //可用的连接数据已去掉一个
 59                         useCount--;
 60                         tmp = getConnection();
 61                     }
 62                 }
 63                 else
 64                 {
 65                     //可使用的连接小于连接数量
 66                     if (useCount <= size)
 67                     {
 68                         try
 69                         {
 70                             //创建连接
 71                             tmp = CreateConnection(tmp);
 72                         }
 73                         catch (Exception e)
 74                         {
 75                         }
 76                     }
 77                 }
 78                 //连接为null
 79                 if (tmp == null)
 80                 {
 81                     //达到最大连接数递归调用获取连接否则创建新连接
 82                     if (useCount <= size)
 83                     {
 84                         tmp = getConnection();
 85                     }
 86                     else
 87                     {
 88                         tmp = CreateConnection(tmp);
 89                     }
 90                 }
 91                 return tmp;
 92             }
 93         }
 94         #endregion
 95 
 96         #region 创建连接
 97         private MySqlConnection CreateConnection(MySqlConnection tmp)
 98         {
 99             //创建连接
100             MySqlConnection conn = new MySqlConnection(ConnectionStr);
101             conn.Open();
102             //可用的连接数加上一个
103             useCount++;
104             tmp = conn;
105             return tmp;
106         }
107         #endregion
108 
109         #region 关闭连接,加连接回到池中
110         public void closeConnection(MySqlConnection con)
111         {
112             lock (pool)
113             {
114                 if (con != null)
115                 {
116                     //将连接添加在连接池中
117                     pool.Add(con);
118                 }
119             }
120         }
121         #endregion
122 
123         #region 目的保证所创连接成功,测试池中连接
124         private bool isUserful(MySqlConnection con)
125         {
126             //主要用于不同用户
127             bool result = true;
128             if (con != null)
129             {
130                 string sql = "select 1";//随便执行对数据库操作
131                 MySqlCommand cmd = new MySqlCommand(sql, con);
132                 try
133                 {
134                     cmd.ExecuteScalar().ToString();
135                 }
136                 catch
137                 {
138                     result = false;
139                 }
140 
141             }
142             return result;
143         }
144         #endregion
145     }
146 }
复制代码

2. 使用

复制代码
 1 MySqlConnection conn = null;
 2 for (int i = 1; i <= 100000; ++i)
 3 {
 4         //获取连接
 5         conn = ConnectionPool.getPool().getConnection();
 6         try
 7         {
 8              //数据操作
 9              MySqlCommand cmd = new MySqlCommand("Select * from zhy_testLianJie", conn);
10              MySqlDataReader dr = cmd.ExecuteReader();
11              while (dr.Read())
12              {
13                   Console.WriteLine("ID:" + i + ",姓名:" + dr[1]);
14               }
15               dr.Close();
16               //将连接添加回连接池中
17               ConnectionPool.getPool().closeConnection(conn);
18         }
19         catch (Exception ex)
20         {
21            Console.WriteLine("\n异常信息:\n{0}", ex.Message);
22            break;
23         }
24 }                
复制代码

这里是MySql的使用方法,SqlServer与之相差就是去掉所有对象的“My”,希望可以帮助到大家

转载于:https://www.cnblogs.com/developer-ios/p/10800791.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#中使用SQLite连接池,可以提高应用程序的性能和可伸缩性。以下是一个简单的SQLite连接池实现: ```csharp using System; using System.Collections.Generic; using System.Data.SQLite; namespace SQLiteConnectionPool { public class SQLiteConnectionPool { private readonly string _connectionString; private readonly Queue<SQLiteConnection> _connections; public SQLiteConnectionPool(string connectionString, int poolSize) { _connectionString = connectionString; _connections = new Queue<SQLiteConnection>(poolSize); InitializePool(poolSize); } private void InitializePool(int poolSize) { for (int i = 0; i < poolSize; i++) { var connection = new SQLiteConnection(_connectionString); connection.Open(); _connections.Enqueue(connection); } } public SQLiteConnection GetConnection() { lock (_connections) { if (_connections.Count > 0) { return _connections.Dequeue(); } } var newConnection = new SQLiteConnection(_connectionString); newConnection.Open(); return newConnection; } public void ReleaseConnection(SQLiteConnection connection) { lock (_connections) { _connections.Enqueue(connection); } } public void Dispose() { foreach (var connection in _connections) { connection.Close(); connection.Dispose(); } } } } ``` 在这个示例中,我们创建了一个SQLiteConnectionPool类,它维护了一个SQLite连接的队列。在初始化时,我们创建了一组SQLite连接并将它们添加到队列中。在需要连接时,我们从队列中检索连接,如果没有可用连接,则创建一个新连接。在使用完连接后,我们将其放回到队列中以便下次使用。 使用连接池的示例: ```csharp var connectionString = "Data Source=database.db"; var poolSize = 10; using (var connectionPool = new SQLiteConnectionPool(connectionString, poolSize)) { using (var connection = connectionPool.GetConnection()) { // 使用连接进行数据库操作 } } ``` 在这个示例中,我们创建了一个连接池,然后使用连接池获取一个连接。在使用完连接后,我们将其释放回连接池中。注意,我们使用了using语句来确保连接和连接池在使用完后正确释放资源。 使用连接池可以避免频繁地创建和销毁数据库连接,从而提高应用程序的性能和可伸缩性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值