1 read database算子
在文件OperatorCore.xml中找到read database算子对应的类为DatabaseDataReader。
<operator>
<key>read_database</key>
<class>com.rapidminer.operator.io.DatabaseDataReader</class>
<replaces>DatabaseExampleSource</replaces>
</operator>
1.1 DatabaseDataReader类图
DatabaseDataReader的类图如下。
1.2 ConnectionProvider
DatabaseDataReader实现了接口ConnectionProvider。
这个接口只有一个方法,即提供一个与连接信息有关的类ConnectionEntry。
public interface ConnectionProvider {
public ConnectionEntry getConnectionEntry();
}
1.3 AbstractExampleSource与AbstractReader
DatabaseDataReader继承了类AbstractExampleSource,AbstractExampleSource又继承了AbstractReader。AbstractReader的其他方法不提,它的doWork()方法如下:
@Override
public void doWork() throws OperatorException {
final T result = read();
addAnnotations(result);
outputPort.deliver(result);
}
AbstractReader中没有提供read()的实现,AbstractExampleSource中read()中,实际调用的方法createExampleSet()并没有真正实现。
/** Creates (or reads) the ExampleSet that will be returned by {@link #apply()}. */
public abstract ExampleSet createExampleSet() throws OperatorException;
@Override
public ExampleSet read() throws OperatorException {
return createExampleSet();
}
1.4 DatabaseDataReader的createExampleSet()
DatabaseDataReader重写了read()方法,不过实际调用了父类的read(),然后利用工具类DatabaseHandler处理了一些连接异常和关闭连接的动作。因此DatabaseDataReader还必须实现createExampleSet()。
private DatabaseHandler databaseHandler;
@Override
public ExampleSet read() throws OperatorException {
try {
ExampleSet result = super.read();
return result;
} finally {
if (databaseHandler != null && databaseHandler.getConnection() != null) {
try {
databaseHandler.getConnection().close();
} catch (SQLException e) {
getLogger().log(Level.WARNING, "Error closing database connection: " + e, e);
}
}
}
}
在createExampleSet中,首先通过getResultSet()从实际数据库中获取数据。然后通过getAttribute()从数据中获取属性。最后将数据与属性放入RapidMiner的table中,再将它以exampleSet的格式返回。
MemoryExampleTable顾名思义,数据是存储在内存中。这里是否需要改进?比如表中数据实在过大,不需要一下子获取全部数据,而是通过翻页参数来获取某x行~某y行的数据。
@Override
public ExampleSet createExampleSet() throws OperatorException {
ResultSet resultSet = getResultSet();
MemoryExampleTable table;
try {
List<Attribute> attributes = getAttributes(resultSet);
table = createExampleTable(resultSet, attributes, getParameterAsInt(ExampleSource.PARAMETER_DATAMANAGEMENT), getLogger());
} catch (SQLException e) {
throw new UserError(this, e, 304, e.getMessage());
} finally {
try {