原廠模式串連資料庫__資料庫

來源:互聯網
上載者:User

在項目中通常可能會使用不同的資料來源,可能是SQL Server也可能是ACCESS或者是Oracle,那麼如何保證在使用不同資料來源的時候,使項目代碼更改的代價最小呢?
對,使用原廠模式.在Net1.1的時候,這需要項目實施者自己來完成.在Net2.0中,MS已經新增了幾個用於實施原廠模式的類庫.
首先我現在應用程式目前的目錄下建立Databases目錄,再建立一個Access資料庫與Sqlserver資料庫
其中這2個資料庫的結構都是一樣的,都包含一個SampleData表,有ID,與IntegerValue欄位

然後回到VS中建立一個WinForm項目,然後編輯App.Config檔案如下:

xml version="1.0" encoding="utf-8" ?>

<configuration>
    <connectionStrings>
   
        <add name="SQL Server" providerName="System.Data.SqlClient"       
          connectionString="Data Source=./SQLEXPRESS;AttachDbFilename=|DataDirectory|/Databases/MyData.mdf;Integrated Security=True;User Instance=True" />
        <add name="MS Access" providerName="System.Data.OleDb"
          connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|/Databases/MyData.mdb;Persist Security Info=True" />   
    connectionStrings>

configuration>

然後在主表單中的Button事件中編寫如下代碼

private void getDataButton_Click(object sender, EventArgs e)
        {
            try
            {
                //建立一個新的StopWatch來監視串連效能[Net2.0新增]
                Stopwatch myWatch = new Stopwatch();

                // 開始計算connection and retrieval of data所花費的時間
                myWatch.Start();

                // 選擇要使用的資料來源
                string strDataSource="MS Access";

                // 根據選者的資料來源獲得連接字串的設定物件               
                ConnectionStringSettings objConnectionSettings = ConfigurationManager.ConnectionStrings[strDataSource];

                // 通過設定檔建立資料庫驅動工廠的執行個體
                DbProviderFactory objProviderFactory = DbProviderFactories.GetFactory(objConnectionSettings.ProviderName);

                // 通過資料庫驅動工廠建立DBConnection執行個體
                using (DbConnection objConnection = objProviderFactory.CreateConnection())
                {
               
                // 從 objConnectionSettings 中擷取連接字串
                objConnection.ConnectionString = objConnectionSettings.ConnectionString;

                // 開啟 connection
                objConnection.Open();

                // 通過資料驅動工廠建立 資料配接器和 Command
                DbDataAdapter myAdapter = objProviderFactory.CreateDataAdapter();
                DbCommand myCommand = objProviderFactory.CreateCommand();
               
           
                string myQuery = "SELECT * FROM SampleData";
                DataSet myDataSet = new DataSet();

                myCommand.Connection = objConnection;
                myCommand.CommandText = myQuery;

                myAdapter.SelectCommand = myCommand;

                myAdapter.Fill(myDataSet);
               
                displayDataGridView.DataSource = myDataSet.Tables[0];

                // 停止StopWatch來查看串連和返回資料所花費的時間
                myWatch.Stop();
                elapsedTimeTextLabel.Text = "消耗時間: " +  myWatch.ElapsedMilliseconds.ToString() + " ms";
                providerLabel.Text = "資料驅動: " + objConnectionSettings.ProviderName.ToString();
                connectionStringLabel.Text = objConnectionSettings.ConnectionString.ToString();
            }
            }
            catch
            {
                MessageBox.Show("出現錯誤.", "Alert");
            }
           
        }
    }

這樣,只需要更改strDataSource就可以使用不同的資料來源,而且整個項目都不需要為不同的資料庫而煩惱

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.