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);
}
}