1. 程式人生 > >C#-工廠模式獲得資料庫連線

C#-工廠模式獲得資料庫連線

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

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            SqlConnection conn = null;
            try
            {
                conn = (SqlConnection)GetConnection();
                conn.Open();
                Console.WriteLine("Open");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {                
                conn.Close();
            }
            Console.Read();

        }

        private static DbConnection GetConnection()
        {
            ConnectionStringSettings conSetting = ConfigurationManager.ConnectionStrings["Northwind"];
            DbProviderFactory factory = DbProviderFactories.GetFactory(conSetting.ProviderName);


            DbConnection con = factory.CreateConnection();
            con.ConnectionString = conSetting.ConnectionString;
            return con;

        }
    }
}

 

/*********************App.config******************/

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
    </startup>
  <connectionStrings>
    <add name="Northwind" connectionString="server=.;database=D:\DATABASE\NORTHWND.MDF;uid=sa;pwd=Server2012;"  
         providerName="System.Data.SqlClient"/>
  </connectionStrings>
</configuration>