大家好,
我在思考这行代码:
IDataReader myReader = questDatabase.ExecuteReader(getQuest);
我正在使用 DAAB,但是我不明白 ExecuteReader(DbCommand) 方法返回 IDataReader 接口的含义和用法。
可以有人解释一下吗?
它允许您使用DataReader而无需知道您正在使用哪种类型的DataReader(即SqlDataReader,OleDbDataReader,EtcDataReader
),因此如果将来有一天您想更改正在使用的数据读取器,它不会影响您的逻辑,换句话说,它给您提供了抽象。
例如:
您可以使用
IDbCommand command = GiveMeSomeCommand();
IDataReader r = command.ExecuteReader();
在不知道您使用的提供程序是哪个的情况下,可能会有以下情况:
private static IDbCommand GiveMeSomeCommand()
{
return new OleDbCommand();
}
或者它可以是
private static IDbCommand GiveMeSomeCommand()
{
return new SqlCommand();
}
或者其他什么。
编辑:
你也可以使用DBFactories。
DbProviderFactory factory = GiveMeSomeFactory();
IDbCommand command = factory.CreateCommand();
IDataReader r = command.ExecuteReader();
//and create more objects
IDataAdapter adapter = factory.CreateDataAdapter();
IDbConnection conn = factory.CreateConnection();
然后在其他层中创建您的提供程序。
private DbProviderFactory GiveMeSomeFactory()
{
if(something)
return SqlClientFactory.Instance;
else if(somethingElse)
return OracleFactory.Instance;
else if(notThisAndNotThat)
return MySqlFactory.Instance;
else
return WhateverFactory.Instance;
}
SqlDataReader
对象的对象,使您能够执行像Read()
这样的方法,并实现IDisposable
和IDataRecord
接口。IDataReader
,可以执行所有 IDataReader
的方法。