using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Data.Common;
using System.Web.Configuration;

namespace ImpDDal
{
    public class DbConnectionStore
    {
        public static DbConnectionStore TheInstance = new DbConnectionStore();
        public static readonly string DBNAME = System.Web.Configuration.WebConfigurationManager.AppSettings["DBName"];

        private DbConnectionStore()
        {
        }

        public DbConnection GetConnection()
        {
            ConnectionStringSettings cnSettings = DbConnectionStore.TheInstance.GetConnectionStringSettings();
            DbProviderFactory providerFactory = DbProviderFactories.GetFactory(cnSettings.ProviderName);
            DbConnection cn = providerFactory.CreateConnection();
            cn.ConnectionString = cnSettings.ConnectionString;
            try
            {
                cn.Open();
                return cn;
            }
            catch (Exception ex)
            {
                throw new Exception("无法连接到服务器", ex);
            }
        }

        public ConnectionStringSettings GetConnectionStringSettings()
        {
            ConnectionStringsSection connectionStringsSection = WebConfigurationManager.GetSection("connectionStrings") as ConnectionStringsSection;
            ConnectionStringSettingsCollection connectionStrings = connectionStringsSection.ConnectionStrings;
            ConnectionStringSettings connStringSettings = connectionStrings[DBNAME];
            return connStringSettings;
        }
    }
}
