将数据库表备份为XML文件
作者水平有限,如有错误还请指正!
1、注意事项:
1.1 数据库部分
- 本案例采用的数据库管理系统为MySQL
- 数据库表为test数据库中的customers数据表,该表包含五个字段(id,name,email,birth,photo)
- 本案例只备份id、name、email、birth这四个字段,如下:
- id字段是作为xml文件中标签的属性进行备份的
1.2 Java部分
- 本案例需要引入两个API(DOM4j,mysql-connection-java),如需可到我的主页下载(https://download.csdn.net/download/m0_47015897/84346129)
- 需创建一个和数据表对应的类(需封装)
- 目录结构如下:
1.3 JDBC部分
-
连接数据库的参数均保存在jdbc.properties文件中,内容如下(等号两边一定不能有空格):
user=root password=abc123 url=jdbc:mysql://localhost:3306/testcharacterEncoding=utf8&useUnicode=true driverClass=com.mysql.jdbc.Driver
-
jdbc.properties文件保存在src文件夹下 -
本案例涉及到JDBC的接口和类均引用自java.sql包(切记)
1.4 XML部分
- 本案例使用的解析技术为DOM4j
- 转换后的XML文件为:Customers.xml,见上方目录结构(存于src文件夹下)
- 备份的数据记录默认进行了格式美化
2、案例分析
2.1 查询数据库表中的记录
- 该操作可参考我的另一篇博文(https://editor.csdn.net/md/?articleId=123291668),一下内容为基本步骤:
- 读取数据库
- 读取参数(jdbc.popreties)
- 注册连接
- 创建SQL语句
- 使用PreparedStatement进行预编译
- 获取查询结果,将每一条记录封装为Customer对象
- 将Customer对象添加至List集合
- 处理异常(try……catch)
- 关闭资源
2.2 将查询结果输出为XML文件
- 获取LIst集合
- 使用DocumentHelper生成Document对象
- 添加根元素
- 遍历List集合,将集合中的每一个Customer对象添加为根元素的子元素,并将其name,email,birth属性设置为该元素的子元素,将id属性添加为该元素的属性(注:由于id和birth属性均非String类型,需将其转换为String类型)
- 以良好的格式输出(美化输出格式)
- 处理异常(try……catch)
- 关闭资源
2.3 备份测试
3、源码解析
3.1 数据库机构及customers表截图
数据库结构: 数据表:
3.2 Customer.java
- 该代码可以直接通过快捷键生成(eclipse快捷键为Alt+Shift+S)
package com.Etui.JDBCUtils;
import java.sql.Date;
public class Customer {
private int id;
private String name;
private String email;
private Date birth;
public Customer() {
super();
}
public Customer(int id, String name, String email, Date birth) {
super();
this.id = id;
this.name = name;
this.email = email;
this.birth = birth;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
@Override
public String toString() {
return "Document [id=" + id + ", name=" + name + ", email=" + email + ", birth=" + birth + "]";
}
}
3.3 jdbc.properties
user=root
password=Hzz15385252813
url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useUnicode=true
driverClass=com.mysql.jdbc.Driver
3.4 执行备份的代码(backupExercise.java)
- 注:在本源码中,我对查询操作和转换操作进行了封装,即分别写为独立的函数;
package com.Etui2.backupDatebaseTable;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
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;
import org.junit.Test;
import com.Etui.JDBCUtils.Customer;
public class backupExercise {
@Test
public void backupTest() {
customersForXml();
}
public void customersForXml() {
XMLWriter writer = null;
try {
List<Customer> list = getCustomers();
Document doc = DocumentHelper.createDocument();
Element root = doc.addElement("Customers");
for(Customer document : list) {
Element customer = root.addElement("Customer");
Element name = customer.addElement("name");
Element email = customer.addElement("email");
Element birth = customer.addElement("birth");
customer.addAttribute("id", String.valueOf(document.getId()));
name.setText(document.getName());
email.setText(document.getEmail());
birth.setText(String.valueOf(document.getBirth()));
}
OutputFormat format = OutputFormat.createPrettyPrint();
writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream("src/Customers.xml"), "UTF-8"), format);
writer.write(doc);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(writer != null) {
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public List<Customer> getCustomers() {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
Properties prop = new Properties();
prop.load(is);
String user = prop.getProperty("user");
String password = prop.getProperty("password");
String url = prop.getProperty("url");
String driverClass = prop.getProperty("driverClass");
Class.forName(driverClass);
conn = DriverManager.getConnection(url, user, password);
String sql = "select id, name, email, birth from customers";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
List<Customer> list = new ArrayList<Customer>();
while(rs.next()) {
Customer cust = new Customer();
for(int i = 0; i < columnCount; i++) {
Object columnValue = rs.getObject(i + 1);
String columnLabel = rsmd.getColumnLabel(i + 1);
Field field = Customer.class.getDeclaredField(columnLabel);
field.setAccessible(true);
field.set(cust, columnValue);
}
list.add(cust);
}
list.forEach(System.out::println);
return list;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(ps != null) {
ps.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(rs != null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return null;
}
}
3.5 备份结果文件(Customers.xml)
<?xml version="1.0" encoding="UTF-8"?>
<Customers>
<Customer id="1">
<name>汪峰</name>
<email>wf@126.com</email>
<birth>2010-02-02</birth>
</Customer>
<Customer id="2">
<name>王菲</name>
<email>wangf@163.com</email>
<birth>1988-12-26</birth>
</Customer>
<Customer id="3">
<name>林志玲</name>
<email>linzl@gmail.com</email>
<birth>1984-06-12</birth>
</Customer>
<Customer id="4">
<name>汤唯</name>
<email>tangw@sina.com</email>
<birth>1986-06-13</birth>
</Customer>
<Customer id="5">
<name>成龙</name>
<email>Jackey@gmai.com</email>
<birth>1955-07-14</birth>
</Customer>
<Customer id="6">
<name>迪丽热巴</name>
<email>reba@163.com</email>
<birth>1983-05-17</birth>
</Customer>
<Customer id="7">
<name>刘亦菲</name>
<email>liuyifei@qq.com</email>
<birth>1991-11-14</birth>
</Customer>
<Customer id="8">
<name>陈道明</name>
<email>bdf@126.com</email>
<birth>2014-01-17</birth>
</Customer>
<Customer id="10">
<name>周杰伦</name>
<email>zhoujl@sina.com</email>
<birth>1979-11-15</birth>
</Customer>
<Customer id="12">
<name>黎明</name>
<email>LiM@126.com</email>
<birth>1998-09-08</birth>
</Customer>
<Customer id="13">
<name>张学友</name>
<email>zhangxy@126.com</email>
<birth>1998-12-21</birth>
</Customer>
<Customer id="16">
<name>朱茵</name>
<email>zhuyin@126.com</email>
<birth>2014-01-16</birth>
</Customer>
<Customer id="18">
<name>贝多芬</name>
<email>beidf@126.com</email>
<birth>2014-01-17</birth>
</Customer>
<Customer id="20">
<name>无情哈拉少</name>
<email>zelian@baidu.com</email>
<birth>2010-10-10</birth>
</Customer>
<Customer id="21">
<name>普京</name>
<email>putin@666.com</email>
<birth>1952-10-07</birth>
</Customer>
<Customer id="25">
<name>金晶</name>
<email>jinjing@qq.com</email>
<birth>2013-12-02</birth>
</Customer>
<Customer id="31">
<name>王峰</name>
<email>wf@126.com</email>
<birth>2010-02-02</birth>
</Customer>
<Customer id="32">
<name>刘大山</name>
<email>lds@123.com</email>
<birth>2012-02-03</birth>
</Customer>
<Customer id="33">
<name>刘盼</name>
<email>liupan@136.com</email>
<birth>1999-02-02</birth>
</Customer>
<Customer id="34">
<name>郭婷</name>
<email>jiaxin@163.com</email>
<birth>2002-12-23</birth>
</Customer>
</Customers>
Over!
|