本文是用.net实现的数据库链接池,大体体现了数据库链接池的实现思想,ADO.NET已经提供了很好的链接池维护,所以本程序基本没有什么实用价值:
1.链接池管理类
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Collections;
using System.Configuration;
/// <summary>
/// DbConnectionPool 的摘要说明
/// </summary>
namespace dbopr
{
public class DbConnectionPool
{
//定义存放数据库链接的队列
private static Queue connections=new Queue();
//数据库参数
private static string ConnString = ""; //链接字符串
//链接池参数
private static int InitSize = 20; //初始化链接池大小
private static int MaxSize = 100; //最大链接数
private static int QueueSize = 50; //队列中最大维护的链接数
private static int ConnNum = 0; //系统维护的链接总数
//定义数据库类型,1表示为SqlServer数据库,2表示其它的OLE DB;默认为SqlServer
private static int DbType = 1;
public static int DbType
{
set
{
DbType = value;
}
}
private DbConnectionPool()
{
try{
ConnString = Configuration.connectionStrings["DbSource"].connectionString;
InitSize = int.Parse(Configuration.connectionStrings["InitSize"].connectionString);
MaxSize = int.Parse(Configuration.connectionStrings["MaxSize"].connectionString);
QueueSize = int.Parse(Configuration.connectionStrings["QueueSize"].connectionString);
DbType = int.Parse(Configuration.connectionStrings["DbType"].connectionString);
initPool();
}
catch(Exception e) {
}
}
//初始化链接池
private static void initPool(){
int i;
for (i = 1; i <= InitSize; i++) {
if (DbType == 1)
connections.Enqueue(newSqlConn());
else
connections.Enqueue(newOleConn());
}
}
//获取一个Sql Server链接对象
private static SqlConnection newSqlConn()
{
ConnNum++;
return new SqlConnection(ConnString);
}
//获取一个OLE DB链接对像
private static OleDbConnection newOleConn()
{
ConnNum++;
return new OleDbConnection(ConnString);
}
//获取一个数据库链接
public static IDbConnection getConn() {
if (connections.Count == 0) //如果队列中链接用完,则新建一个链接放入队列
{
if (ConnNum > MaxSize) //如果当前活动链接达到最大,则等待链接
return null;
else
{
if (DbType == 1)
connections.Enqueue(newSqlConn());
else
connections.Enqueue(newOleConn());
return connections.Dequeue();
}
}
else
return connections.Dequeue();
}
//释放一个活运链接
public static void reConn(IDbConnection conn) {
if (connections.Count > QueueSize) //如果队列中元素个数已达到最大,则关闭链接
conn.Close();
else
connections.Enqueue(conn);
}
//销毁链接池
public static void ClearPool() {
while(connections.Count>0)
(IDbConnection)connections.Dequeue().Close();
}
}
}
2.链接生成类
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Configuration;
using System.Web;
/// <summary>
/// DbConn 的摘要说明
/// </summary>
namespace dbopr
{
public class DbConnection
{
private static IDbConnection conn;
public DbConnection()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
public static SqlConnection getSqlConn()
{
//获取链接池中的Sql Server的链接
conn = DbConnectionPool.getConn();
return (SqlConnection)conn;
}
public static OleDbConnection getOleConn() {
//获取其它OLE DB的链接
conn = DbConnectionPool.getConn();
return (OleDbConnection)conn;
}
public static void Close() {
//放回用过的链接
DbConnectionPool.reConn(conn);
}
}
}