也許很多人都有和我一樣的經驗,客戶的數據庫管理系統可能暫時沒有定下來,或者是 受服務器的限制,在項目快進行完時需要更換DBMS。由於我們的系統中大量的存在數據庫連接,如果類設計不恰當的話,造成數據庫連接和其他邏輯的緊耦合,在更改DBMS時就會有很大的麻煩。我們幾乎要搜索遍程序的每一個角落。
設計模式裡有一種很好的解決方案:把數據庫連接做成一個抽象工廠(IDbFactory),每種具體的數據庫接口就是具體實現工廠(SqlFactory,OdbcFactory,OleDbFactory),程序中所有的數據庫連接都由這個工廠來生產(IDbFactory.GetCon())。我們只要在數據庫操作類(DbOperater)控制抽象工廠的實例(IDbFactory factory = new SqlFactoy/OdbcFactory/OleDbFactory),只修改一處代碼,就可以自由地給系統更換DBMS了。
抽象工廠 IDbFactory.cs
using System.Data;
interface IDBFactory ...{
IDBConnetction GetCon();
IDBCommand GetCmd();
IDataAdapter GetAdapter(IDBCommand cmd);
string GetDateTimeStr(string datetime);
}
注:由於不同的DBMS中關於時間的處理SQL語法不同,所以要有一個方法:
string GetDateTimeStr(string datetime);
數據庫操作類
using System.Data;
using System.Configuration;
public class DBOperator ...{
private IDBFactory _factory;
private IDbConnection _con;
public DBOperator() ...{
this._factory = new SqlFactory();
this._con = _factory.GetCon();
_con.ConnectionString = ConfigurationManager.ConnectionStrings["sqlCon"].ConnectionString;
}
public void Open() ...{
_con.Open();
}
public void Close() ...{
_con.Close();
}
public IDbConnection GetCon()
...{
return _con;
}
public DataSet ExecSql(string sqlStr) ...{
IDbCommand cmd = _factory.GetCmd();
cmd.Connection = this._con;
cmd.CommandText = sqlStr;
IDataAdapter adapter = _factory.GetAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds);
return ds;
}
public DataSet ExecSql(string sqlStr1, string datetime, string sqlStr2) ...{
IDbCommand cmd = _factory.GetCmd();
cmd.Connection = this._con;
cmd.CommandText = sqlStr1+_factory.GetDateTimeStr(datetime)+sqlStr2;
IDataAdapter adapter = _factory.GetAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds);
return ds;
}
public DataSet ExecSql(string sqlStr1,string sqlStr2, params string[] datatime)
...{
IDbCommand cmd = _factory.GetCmd();
cmd.Connection = this._con;
string dtfIEld = "";
for (int i = 0; i < datatime.Length; i++)
...{
dtfIEld += "," + _factory.GetDateTimeStr(datatime[i]);
}
dtfield = dtfIEld.Substring(1);
cmd.CommandText = sqlStr1 + dtfIEld + sqlStr
IDataAdapter adapter = _factory.GetAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds);
return ds;
}
}
SQL Server 連接 工廠
using System.Data;
using System.Data.SqlClIEnt;
public class SqlFactory : IDBFactory ...{
public IDBConnection GetCon() ...{
return new SqlConnection();
}
public IDBCommand GetCmd() ...{
return new SqlCommand();
}
public IDataAdapter GetAdapter() ...{
return new SqlAdapter();
}
public string GetDateTimeStr(string datetime) ...{
return "''"+datetime+"''"
}
}
Access 連接工廠
using System.Data;
using System.Data.OleDb;
public class OleDbFactory : IDBFactory ...{
public IDBConnection GetCon() ...{
return new OleDbConnection();
}
public IDBCommand() GetCmd() ...{
return new OleDbCommand();
}
public IDataAdapter(IDBCommand cmd) ...{
return new OleDbDataApdaper(cmd);
}
public string GetDateTimeStr(string datetime) ...{
return "#"+datetime+"#"
}
}