package org.xiaoyu.jdbc;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Properties;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
public class Dom4jJdbc {
public static void main(String[] args) throws Exception {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
System.out.println("Load the embedded driver");
Connection conn = null;
Properties props = new Properties();
props.put("user", "user1");
props.put("password", "user1");
// create and connect the database named helloDB
conn = DriverManager.getConnection("jdbc:derby:helloDB;create=false",
props);
System.out.println("connect to helloDB");
DatabaseMetaData m = conn.getMetaData();
Document document = DocumentHelper.createDocument();
Element root = document.addElement("hibernate-mapping");
Element classElement = root.addElement("class")
.addAttribute("name", "org.xiaoyu.User")
.addAttribute("table", "helloDB");
ResultSet rs = m.getColumns(null, null, "HELLOTABLE", null);
while (rs.next()) {
System.out.println(rs.getString("COLUMN_NAME"));
// 加入获取的列名
classElement.addElement("property").addAttribute("name",
rs.getString("COLUMN_NAME"));
}
OutputFormat format = OutputFormat.createPrettyPrint();
XMLWriter writer = new XMLWriter(new FileWriter("User2.xml"), format);
writer.write(document);
writer.close();
rs.close();
conn.close();
try { // perform a clean shutdown
DriverManager.getConnection("jdbc:derby:;shutdown=true");
} catch (SQLException se) {
System.out.println("Database shut down normally");
}
}
}
derby数据库。dom4j根据数据库表,生成对应的XML文件。