c#中的資料庫訪問工廠

來源:互聯網
上載者:User

     上午看到一個兄弟的文章,很辛苦的想實現不改代碼只改配置來訪問不同類型的資料庫,自己去實現原廠模式。精神可嘉,但是殊不知c#已經自己為不同類型資料庫的訪問做了一個工廠。在這裡我就把使用工廠的例子貼出來供不知道的兄弟參考一下,高手們可以忽略了。

      首先是設定檔:其中的providerName就是指定的不同資料庫類型

<connectionStrings>
        <add name="..."  connectionString=" ..." providerName="System.Data.OleDb" />

        <add name="..."  connectionString=" ..." providerName="System.Data.SqlClient" />
    </connectionStrings>

      下面看一下使用工廠的這個類:

     class DataBaseFac
    {
        private DbConnection cnn;//抽象類別型
        private DbCommand cmd;//抽象類別型
        private DbProviderFactory provider;
        public DataBaseFac()
        {

            //從設定檔中取出標示資料庫類型的字串
            string providerName = ConfigurationManager.ConnectionStrings[1].ProviderName;

            //根據上一部的結果工廠建立一個對應的執行個體
            provider = DbProviderFactories.GetFactory(providerName);

            //使用該執行個體就可以建立對應的connection,command 和adapater對象了

            //調試的時候可以看到這幾個對象都變成了相應於資料庫類型的
            cnn = provider.CreateConnection();
            cnn.ConnectionString = ConfigurationManager.ConnectionStrings[1].ConnectionString;
            cmd = provider.CreateCommand();
            cmd.Connection = cnn;
        }

        //執行一次查詢,返回資料表

        public DataTable ExcuteQuery(string queryString)
        {
            DataTable result = new DataTable();
            DbDataAdapter adapter = provider.CreateDataAdapter();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = queryString;
            adapter.SelectCommand = cmd;
            try
            {
                cnn.Open();
                adapter.Fill(result);
            }
            catch
            {
                result = null;
            }
            finally
            {
                cnn.Close();
            }
            return result;

        }

        以上只是簡單的應用,並沒有做比較進階的封裝,只供不知道的兄弟參考。

        順便說說,上午看到那個兄弟的文章用swith case語句來實現不同的建立connection ,command 和adapater的方法,然後說是Factory 方法的實現。其實這是完全錯誤的,原廠模式的提出就是為了避免這麼多swith case造成的麻煩。以後有時間我會把幾個常用的模式的提出原因和應用場合總結一下用C#做幾個例子給不清楚的兄弟貼出來的。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.