ADO.NET:连接池

来源:互联网 发布:java从入门到精通 pdf 编辑:程序博客网 时间:2024/04/28 22:47

此示例阐释如何建立到数据源的连接池。需要进行此操作来部署高性能的应用程序。在此示例中,池是在连接字符串中建立起来,并由 SqlConnection 自动管理的。

 
VB ConnectionPooling.aspx

[运行示例] | [查看源代码]

在此示例中,在构造 SqlConnection 时在连接字符串中指定池特性,如以下的代码示例中所示。请注意:池处理是隐式的,除非将其禁用,否则将自动进行池处理。因此,"true"是默认的池关键词 (pooling=true)。

String connString;// Specification in the connection string:// Please note: Pooling is implicit, you automatically get it unless you disable it. //              Therefore, "true" is the default for the pooling keyword (pooling=true).   // Connection Reset:    False// Connection Lifetime: 5// Enlist:              true// Min Pool Size:       1// Max Pool Size:       50connString = "server=(local)//VSdotNET;Trusted_Connection=yes;database=northwind;" +             "connection reset=false;" +             "connection lifetime=5;" +             "min pool size=1;" +             "max pool size=50";SqlConnection myConnection1 = new SqlConnection(connString);SqlConnection myConnection2 = new SqlConnection(connString);SqlConnection myConnection3 = new SqlConnection(connString);
C# VB  

现在,我们有了使用池中的若干连接的代码。首先,打开两个连接并返回这两个到池的连接。然后,从池中打开三个连接,并返回所有这三个到池的连接。

// Open two connections. One is from the pool (see min pool size), the other is created.Console.WriteLine ("Open two connections.");myConnection1.Open();myConnection2.Open();// Now there are two connections in the pool that matches the connection string.// Return the both connections to the pool. Console.WriteLine ("Return both of the connections to the pool.");myConnection1.Close();myConnection2.Close();// Get a connection out of the pool.Console.WriteLine ("Open a connection from the pool.");myConnection1.Open();// Get a second connection out of the pool.Console.WriteLine ("Open a second connection from the pool.");myConnection2.Open();// Open a third connection.Console.WriteLine ("Open a third connection.");myConnection3.Open();// Return the all connections to the pool.  Console.WriteLine ("Return all three connections to the pool.");myConnection1.Close();myConnection2.Close();myConnection3.Close();
C# VB  

池连接的模型与非池连接的相似。但是,当断开池连接来将其释放回池时,调用 Close 是特别重要的。

原创粉丝点击