有一個代碼可以用xml從數據庫中導出數據。Java如何從整個數據庫導出數據?
public class DataExtractor{
private final String login, passwd, host;
public DataExtractor(String login, String passwd, String host){
this.login = login;
this.passwd = passwd;
this.host = host;
}
public String getTableData(String tableName) throws SQLException, ClassNotFoundException {
Connection con = null;
Statement st = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql:///" + host, login, passwd);
st = con.createStatement();
rs = st.executeQuery("select * from " + tableName);
ResultSetMetaData rsmd = rs.getMetaData();
int colCount = rsmd.getColumnCount();
StringBuilder b = new StringBuilder("<table>\n");
int num = 1;
while (rs.next()) {
b.append("<row>");
b.append("<num>").append(num++).append("</num>");
for (int i = 1; i <= colCount; i++) {
String columnName = rsmd.getColumnName(i);
b.append('<').append(columnName).append('>');
b.append(rs.getObject(i));
b.append("</").append(columnName).append('>');
}
b.append("</row>\n");
}
b.append("</table>");
return b.toString();
} catch (SQLException e) {
throw e;
} catch (ClassNotFoundException e) {
throw e;
} finally {
if (rs != null)
try {
rs.close();
} catch (SQLException e) {
}
if (st != null)
try {
st.close();
} catch (SQLException e) {
}
if (con != null)
try {
con.close();
} catch (SQLException e) {
}
}
}
}
但這類出口額從給定的表只有數據,如何確保從整個數據庫(即所有表)導出的數據,而不是從某個特定表。也就是說,應該得到的輸出XML文件類型:
<database>
<table1>
<id> </ id>
<Name> </ Name>
...
</ table1>
<table2>
...
</ table2>
</ database>
你可能想看看你的DBMS的文檔。大多數提供了一個內置的導出功能 - 無論是在CVS,XML或二進制文件... – home 2012-07-08 07:24:07