有一个代码可以从 xml 中的数据库中导出数据。
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>