import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.*;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;
public class XMLfromMYSQL {
public static void main(String[] args) {
ResultSet rs = null;
Statement stmt = null;
Connection conn = null;
try {
String URL = "jdbc:mysql://127.0.0.1:3306/multi";
String user = "root";
String password = "123";
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(URL, user, password);
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT Rbh,Rgly,Rlx,Rbz FROM RJBB");
Document document = new Document(new Element("RJBB"));// 创建文档,用表名做根元素
int count = 1;
String sElement = "";
ResultSetMetaData rsmd = rs.getMetaData(); // 获取字段名
int numberOfColumns = rsmd.getColumnCount(); // 获取字段数
while (rs.next()) {
sElement = "第" + count + "行";
Element element0 = new Element(sElement); // 创建元素 生成JDOM树
document.getRootElement().addContent(element0);
for (int i = 1; i <= numberOfColumns; i++) {
String date = rs.getString(i); // 代码转换
Element element = new Element(rsmd.getColumnName(i))
.setText(date);
element0.addContent(element);
}
count++;
}
rs.close();
XMLOutputter outp = new XMLOutputter();
try {
outp.output(document, new FileOutputStream("D:\\MYSQL.xml"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} // 输出XML文档
System.out.println("XML 文档生成完毕!");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (rs != null) {
rs.close();
rs = null;
}
if (stmt != null) {
stmt.close();
stmt = null;
}
if (conn != null) {
conn.close();
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}