上午看到一個兄弟的文章,很辛苦的想實現不改代碼只改配置來訪問不同類型的資料庫,自己去實現原廠模式。精神可嘉,但是殊不知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#做幾個例子給不清楚的兄弟貼出來的。