我认为这不会涉及大量工作,但让您从这里开始是一种快速的方法,您可以扩展它:
- 将需要一个代表您的不同提供者的枚举,即 SQL、Access 等
- 可能称为 DataAccess 的类在构造函数中接受您的提供程序类型:
public class DataAccess
{
private DbProviderFactory factory;
private DbConnection connection;
public enum Provider
{ SQL, Access }
public DataAccess(Provider provider)
{
switch (provider)
{
case Provider.Ole:
factory = DbProviderFactories.GetFactory("System.Data.OleDb");
break;
case Provider.Sql:
factory = DbProviderFactories.GetFactory("System.Data.SqlClient");
break;
}
this.connection = factory.CreateConnection();
}
public DbDataReader GetDataReader(string statement, params DbParameter[] parameters)
{
using (DbCommand command = factory.CreateCommand())
{
if (connection.State == ConnectionState.Closed)
{
connection.Open();
}
command.CommandText = statement;
command.Connection = connection;
parameters.ToList().ForEach(x => command.Parameters.Add(x));
return command.ExecuteReader(CommandBehavior.CloseConnection);
}
}
}
每当您想创建命令或参数等时,您都可以使用工厂变量。
DbCommand command = Factory.CreateCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = procedureName;
command.Connection = connection;
如果您想要更具体的 Access 自定义代码,那么您需要使用继承模型,但我想 SQL 和 Access 有共同的语法,即相同的 SELECT、INSERT 命令等?