当前位置: 代码迷 >> C# >> 关于ADO.NET的不解
  详细解决方案

关于ADO.NET的不解

热度:71   发布时间:2016-05-05 04:39:21.0
关于ADO.NET的疑惑

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestADO
{
    class Db : IDisposable
    {
        private SqlConnection connection;
        public Db()
        {
            this.connection = new SqlConnection("Data Source=.;Initial Catalog=Test;Integrated Security=SSPI;");
            connection.Open();
        }

        public void Select()//代表通过构造器初始化数据库连接的方式
        {
            SqlCommand command = connection.CreateCommand();
            command.CommandText = "select Name from JiLu where ID=2";
            SqlDataAdapter dataAdapter = new SqlDataAdapter(command);
            DataSet dataSet = new DataSet();
            dataAdapter.Fill(dataSet);
            Console.WriteLine(dataSet.Tables[0].Rows[0]["Name"].ToString());
            
        }

        public void OldSelte()//代表通过new得到数据库连接的方式
        {
            using (SqlConnection connection_ =new SqlConnection("Data Source=.;Initial Catalog=Test;Integrated Security=SSPI;"))
            {
                connection_.Open();
                SqlCommand command = connection_.CreateCommand();
                command.CommandText = "select Name from JiLu where ID=2";
                SqlDataAdapter dataAdapter = new SqlDataAdapter(command);
                DataSet dataSet = new DataSet();
                dataAdapter.Fill(dataSet);
                Console.WriteLine(dataSet.Tables[0].Rows[0]["Name"].ToString());
            }
        }

        public void Dispose()
        {
            Console.WriteLine("释放DB!");
            connection.Close();
            connection.Dispose();
        }
    }
}


其实我想问的是Select()和OldSelte()两种数据库查询那种比较好,考虑性能和稳定
------解决思路----------------------
数据库逻辑连接要迅速释放,否则就会在生产环境并发程序上频繁遇到“连接池满,没有可用的数据库连接”的问题。在读写完毕就要立刻释放,而你的 Select() 没有立刻调用 Dispose,所以它实际上是有bug的。

另外,就算是你的Select方法加上一行代码代码调用 Dispose,它也不能保证即使是在读写数据库抛出异常时也能确保及时地调用Dispose。

因此,你的 Select 应该删除掉。只留下 OldSelte 就可以了!
  相关解决方案