有没有办法从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并且我希望从DatabaseB内部连接DatabaseA和TableB中的TableA,并将结果传输到Excel文件,该怎么办?我该怎么做呢?
编辑:如果数据库在不同的服务器上怎么办?
答案 0 :(得分:1)
如果 数据库位于同一个数据库服务器和中,您的用户具有两者的权限,您可以做像
这样的事情<强> Mysql的强>
SELECT * FROM db1.table1 A INNER JOIN db2.table2 B ON A.col = B.col
SQL-Server (默认架构dbo
)
SELECT * FROM db1.dbo.table1 A INNER JOIN db2.dbo.table2 B ON A.col = B.col
如果数据库位于不同的服务器上,则您的选项会受到更多限制。
对于SQL-Server,您可以添加“链接服务器” - 允许通过linkname...table
进行访问。