1.WriteXml.java:
代码如下:
package cn.gov.csrc.xml;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.List;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import cn.gov.csrc.jdbc.DatabaseConnection;
/**
* @function 使用Jdom查询数据库把数据写入xml文件中
* @author admin
*
*/
public class WriteXml {
public static void WriterFileToXml(){
//创建一个xml文件
File file = new File("D://user.xml");
//创建数据库连接
Connection conn = DatabaseConnection.getConn();
String sql = "select * from user";
try {
Statement st = conn.createStatement();//创建预处理对象
ResultSet rs = st.executeQuery(sql);//获得结果集
Element root = new Element("users");//创建根元素
while (rs.next()) {
Element user = new Element("user");//创建子元素
root.addContent(user);//添加子元素到根节点
Element id = new Element("ID");//创建叶子节点
id.setText(rs.getString("ID"));//给叶子节点赋值
user.addContent(id);//添加叶子节点到父节点
Element ename = new Element("USERNAME");
ename.setText(rs.getString("USERNAME"));//给叶子节点赋值
user.addContent(ename);
Element password = new Element("PASSWORD");//创建叶子节点
password.setText(rs.getString("PASSWORD"));//给叶子节点赋值
user.addContent(password);//添加叶子节点到父节点
Element status = new Element("STATUS");
status.setText(rs.getString("STATUS"));//给叶子节点赋值
user.addContent(status);
Element descn = new Element("DESCN");
descn.setText(rs.getString("DESCN"));//给叶子节点赋值
user.addContent(descn);
}
Document doc = new Document();//创建文本对象
doc.addContent(root);//添加树倒文本中
Format format= Format.getCompactFormat();
format.setIndent(" ");
XMLOutputter out = new XMLOutputter(format);//创建输出流
FileWriter fw = new FileWriter(file);//写数据
out.output(doc, fw);//输出到xml文件中
fw.close();//关闭写入流
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
//把数据库的数据写入xml文件中
WriteXml.WriterFileToXml();
}
}
2.连接数据库java类:DatabaseConnection.java:
代码如下复制代码
package cn.gov.csrc.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* 连接数据库
*
* @author admin
*
*/
public class DatabaseConnection {
private static final String driverName = "com.mysql.jdbc.Driver";
private static final String url = "jdbc:mysql://localhost/springdb?autoReconnect=true&useUnicode=true&characterEncoding=UTF8";
private static final String username = "root";
private static final String password = "root";
static {
try {
Class.forName(driverName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConn() {
Connection conn = null;
try {
conn = DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
public static void main(String[] args) {
Connection conn = getConn();
System.out.println(conn);
}
}
更多信息请查看IT技术专栏