ADO.NET复习总结(2)--连接池

1、

2、

3、示例:在一百次循环中,执行数据库连接的打开和关闭,使用stopwatch查看所用的时间。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Diagnostics;
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Stopwatch watch = new Stopwatch();

            watch.Start();
            for (int i = 0; i < 100; i++)
            {
                SqlConnection conn = new SqlConnection("server=.;database=dbtest;uid=sa;pwd=123");
                conn.Open();
                conn.Close();
                conn.Dispose(); 
            }
            watch.Stop();
            label1.Text = watch.ElapsedMilliseconds.ToString();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Stopwatch watch = new Stopwatch();

            watch.Start();
            for (int i = 0; i < 100; i++)
            {
                SqlConnection conn = new SqlConnection("server=.;database=dbtest;uid=sa;pwd=123;Pooling=false");
                conn.Open();
                conn.Close();
                conn.Dispose();
            }
            watch.Stop();
            label2.Text = watch.ElapsedMilliseconds.ToString();

        }
    }
}
View Code

结论:

1.在ADO.NET中的每个应用程序都维护一个连接对象池,每次使用时不会新建对象,而是先从池中获取,得到后直接使用,

如果没有则新建,减少了每次新建的时间

2.在内存中开辟一个集合空间,用于存储空闲的对象,如果每次需要对象时,先从集合中获取,如果获取不到在新建。

3.对象池:提高执行效率

4说明:

(1)两次连接所使用的字符串必须一样

(2)打开使用,使用完成后close()则将连接对象放到连接池中;当使用连接对象时,去连接池中找,有可用的则拿过来用。

(3)如果某个连接对象在使用中没有关闭,又需要使用连接对象,则会重新创建一个新的连接对象,因为此时没有空闲的连接对象。

(4)可以设置备用连接对象数;在连接字符串中设置。

(5)close并不是真的关闭连接,而是将连接对象放入连接池中。

原文地址:https://www.cnblogs.com/mhq-martin/p/8085296.html