【发布时间】:2016-01-14 15:25:23
【问题描述】:
有没有办法从 2 个(或更多)不同的数据库/连接中组合 2 个(或更多)表?
到目前为止,我只能从数据库中导出一个表,而且效果很好:
private void populateWorksheet(Database db, Sheet sheet) {
PreparedStatement preStmt; // An object that represents a precompiled SQL statement. See http://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.html
ResultSet rsltSet; // A table of data representing a DB result set
ResultSetMetaData meta; // An object that can be used to get information about the types and properties of the columns in a ResultSet object
String columnName, data;
Row headerRow, dataRow;
Cell currHeaderCell, currDataCell;
int columnCount, rowCount; // keep track of indices
try {
preStmt = db.getConnection().prepareStatement(columnsQuery);
rsltSet = preStmt.executeQuery();
meta = rsltSet.getMetaData();
columnCount = meta.getColumnCount();
//Creating a Row for columns headings - starts with row 0
headerRow = sheet.createRow(HEADER_ROW_INDEX);
//Get column headings and print them in Excel - on the first row
for(int i = 1; i <= columnCount; i ++) {
columnName = meta.getColumnName(i);
currHeaderCell = headerRow.createCell(i - 1);
currHeaderCell.setCellValue(columnName);
}
rowCount = FIRST_DATA_ROW_INDEX; // 1st row after the header row (data/record starts here)
while(rsltSet.next()) {
dataRow = sheet.createRow(rowCount);
for(int i = 1; i <= columnCount; i ++) {
data = rsltSet.getString(i);
currDataCell = dataRow.createCell(i - 1);
currDataCell.setCellValue(data);
}
rowCount ++;
}
}
catch (SQLException e) {
e.printStackTrace();
}
}
但是,如果我的应用程序连接到 DatabaseA 和 DatabaseB,并且我想将来自 DatabaseA 的 TableA 和来自 DatabaseB 的 TableB 进行内连接,并将结果传输到 Excel 文件,该怎么办。我该怎么做呢?
编辑:如果数据库在不同的服务器上怎么办?
【问题讨论】:
-
您不能直接这样做,您需要查询两个数据源并在代码中“加入”它们。或者使用可以连接到其他数据库服务器的数据库服务器。
-
感谢您的回复。我如何在代码中“加入”它们?
-
您使用的是哪个 RDBMS?至少 Oracle 支持在同一查询中连接通过数据库链接访问的本地表和远程表中的数据。
-
我被要求对来自不同数据库的表进行内部连接。可能来自 Oracle、Access 甚至 SAS 数据集。