在項目中通常可能會使用不同的資料來源,可能是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就可以使用不同的資料來源,而且整個項目都不需要為不同的資料庫而煩惱