使用连接池
----------如果是OleDbConnection则连接池由提供程序自动处理
---------- 如果是SqlConnection类则连接池被隐式管理但是也可以自己管理
在连接字符串中指定
pooling=true;
connection lifeting=5; //声明周期
min pool size=1; //最小连接数
max pool size=50; //最大连接数
下面看一个例子:
<%@ Page Language="C#" ContentType="text/html" ResponseEncoding="gb2312" Debug="True"%>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<html>
<head>
<title>无标题文档</title>
<script runat="server">
public TimeSpan PoolTest(string strcon)
{
int nConNum=50;
DateTime dtStart=DateTime.Now;
for(int i=1;i<=nConNum;i++)
{
using(SqlConnection con=new SqlConnection(strcon))
{
con.Open();
con.Close();
}
}
DateTime dtEnd=DateTime.Now;
TimeSpan ts=dtEnd-dtStart;
return ts;
}
void btnTest_Click(object Source,EventArgs e)
{
//不使用连接池创建连接字符串
string strConUnusePool="Server=.;DataBase=aspnetdb;uid=sa;Password=zhangjie;"+"pooling=false";
//使用连接池创建连接字符串
string strConUsePool="Server=.;DataBase=aspnetdb;uid=sa;Password=zhangjie;"+"pooling=true;connection lifetime=5";
TimeSpan pt=PoolTest(strConUnusePool);
lblUnusePool.Text=pt.Milliseconds.ToString(); //计算出不使用连接池连接使用的毫秒数
lblUsePool.Text=this.PoolTest(strConUsePool).Milliseconds.ToString(); //计算出不使用连接池连接使用的毫秒数
}
</script>
<style type="text/css">
<!--
.STYLE1 {color: #FF0000}
-->
</style>
</head>
<body>
<form runat="server">
<table width="367" height="149" border="1" align="center" cellpadding="0" cellspacing="1" bordercolor="#0000FF" bgcolor="#FFFFCC">
<tr>
<td width="165" height="33"> <div align="center">Use Pool</div></td>
<td width="170"><div align="center">Unuse Pool</div></td>
</tr>
<tr>
<td height="77" align="center"><span class="STYLE1">
<asp:Label ID="lblUsePool" runat="server"/>
</span> </td>
<td align="center"><span class="STYLE1">
<asp:Label ID="lblUnusePool" runat="server"/>
</span></td>
</tr>
<tr>
<td height="37" colspan="2"><div align="center">
<asp:Button BackColor="#CC0000" BorderColor="#0000FF" Font-Bold="true" ForeColor="#FFFFFF" ID="btnTest" runat="server" Text="测 试" Width="200" OnClick="btnTest_Click"/>
</div></td>
</tr>
</table>
</form>
</body>
</html>