你应该搜索和研究设计模式。看看这个链接。另请查看LLBLGen
如果您想选择自己的解决方案,那么您必须分层工作。定义松散耦合的数据访问层 (DAL)。一种方法是使用接口。为数据库连接定义一个接口,然后让 DBMS 的每个类来实现它。然后,您可以在以下几行中获取数据库连接字符串。
来源:
public static IDbConnection GetConnection(string connectionName)
{
ConnectionStringSettings ConnectString = ConfigurationManager.ConnectionStrings[connectionName];
//Use a Factory class, to which you pass the ProviderName and
//it will return you object for that particular provider, you will have to implement it
DbProviderFactory Factory = DbProviderFactories.GetFactory(ConnectString.ProviderName);
IDbConnection Connection = Factory.CreateConnection();
Connection.ConnectionString = ConnectString.ConnectionString;
return Connection;
}
然后你可以像这样使用它:
public static DataTable GetData()
{
using (IDbConnection Connection = GetConnection("SiteSqlServer"))
{
IDbCommand Command = Connection.CreateCommand();
Command.CommandText = "DummyCommand";
Command.CommandType = CommandType.StoredProcedure;
Connection.Open();
using (IDataReader reader = Command.ExecuteReader())
{
DataTable Result = new DataTable();
Result.Load(reader);
return Result;
}
}
}