从mysql读取数据结果集封装成xml文件,并解析xml文件方便插入其他数据库(oracle,sqlserver,国产数据库)

1. 从mysql读取数据结果集封装成xml文件

/**
     * 使用SAX的方式在遍历结果集的同时生成xml文件。
     * @param rs
     * @param filePath
     * @throws Exception
     */
    public static void resultSet2XML(ResultSet rs, String filePath) throws Exception{

        // 创建一个SAX转换工厂
        SAXTransformerFactory fac = (SAXTransformerFactory)SAXTransformerFactory.newInstance();
        // 创建一个TransformerHandler实例
        TransformerHandler handler = fac.newTransformerHandler();
        // 创建一个handler转换器
        Transformer transformer = handler.getTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"no"); // 是否忽略xml声明
        transformer.setOutputProperty(OutputKeys.METHOD,"xml");
        transformer.setOutputProperty(OutputKeys.ENCODING,"UTF-8"); // 设置输出采用的编码方式
        transformer.setOutputProperty(OutputKeys.INDENT,"yes"); // 是否自动添加额外的空白 换行
        transformer.setOutputProperty(OutputKeys.STANDALONE,"no");
        // 创建一个Result实例连接到XML文件
        FileOutputStream fos = new FileOutputStream(filePath);
        Result resultxml = new StreamResult(fos);
        handler.setResult(resultxml);
        ResultSetMetaData rsmd = rs.getMetaData();
        String value = "";
        byte[] byteValue = null;
        // 打开doc对象
        handler.startDocument();
        // 创建一个属性实例
        AttributesImpl atts = new AttributesImpl();
        // 创建元素节点,并构建XML内容 handler.startElement(uri, 命名空间, 元素名, 属性); //没有则填null
        handler.startElement("","","RECORDS",atts);
        if(rs.next()){
            rs.previous();
            while(rs.isLast() == false){
                rs.next();
                atts.clear();
                handler.startElement("","","RECORD",null);
                for(int i=1;i<=rsmd.getColumnCount();i++){
                    int columnType = rsmd.getColumnType(i);
                    System.out.println("columnType:"+columnType);

                    String columnName = rsmd.getColumnLabel(i);//.toLowerCase();
                    System.out.println("columnName:"+columnName);
                    handler.startElement("","",columnName,null);

                    if(columnType == -4){
                        byteValue = rs.getBytes(i);
                        if(byteValue != null && byteValue.length>0){
                            System.out.println("byteValue:"+encode(byteValue));
                        }
                    }else{
                        value = rs.getString(i);
                        System.out.println("value:"+value);
                    }
                    if(value == null && (byteValue == null || byteValue.length == 0)){
                        // 设置标签内容
                        handler.characters(null,0,0);
                    }else{
                        // 设置标签内容
                        if(value != null){
                            handler.characters(value.toCharArray(),0,value.length());
                        }
                        if(byteValue!= null ){
                            handler.characters(encode(byteValue).toCharArray(),0, byteValue.length);
                        }
                    }
                    // // 结束hanlder.endElement("", "", 元素名)
                    handler.endElement("","",columnName);
                    value = null;
                    byteValue = null;
                }
                handler.endElement("","","RECORD");
            }
        }
        handler.endElement("","","RECORDS");
        // 关闭doc对象
        handler.endDocument();
        fos.close();
    }

    /**
     * byte数组 转换为 Base64字符串
     */
    public static String encode(byte[] data) {
        String body =  new BASE64Encoder().encode(data);
        if(body.contains("\r\n")){
            body = body.replace("\r\n","");
        }
        return body;
    }

2. 解析xml文件封装成List

/**
     * SAX将xml转sql语句
     *  备注: SAX由于是事件驱动解析,相当于从上往下解析,所以继承DefaultHandler重写里面的解析方法
     * @param filePath
     * @throws Exception
     */
    public static void XML2Sql(String filePath) throws Exception{
        File inputFile = new File(filePath);
        // 创建一个SAX解析工厂
        SAXParserFactory factory = SAXParserFactory.newInstance();
        // 创建一个SAX转换工具
        SAXParser saxParser = factory.newSAXParser();
        // 解析XML
        SAXParserHandler handler = new SAXParserHandler();
        saxParser.parse(inputFile, handler);
        List> list = handler.getList();
        for (Map map : list) {
            System.out.println("==================开始=====================");
            for (Map.Entry m : map.entrySet()) {
                System.out.print(m.getKey() + "    ");
                System.out.println(m.getValue());
            }
            System.out.println("==================结束=====================");
        }
    }
SAXParserHandler.java
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SAXParserHandler extends DefaultHandler {
    private Map map = new HashMap<>();
    private List> list = new ArrayList<>();
    private String content = null;

    //文档开始
    @Override
    public void startDocument() throws SAXException {
        System.out.println("文档开始");
    }
    //xml元素的开始
    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
       System.out.println("元素名称="+qName);
    }
    //xml元素内容
    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        content = new String(ch, start, length);
        System.out.println("start="+start);
        System.out.println("元素内容="+content);
    }
    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        if(content.equals("\n")) content="";
        map.put(qName,content);
        if (qName.equals("RECORD")) {
            list.add(map);
            map = new HashMap<>();
        }
    }
    //文档结束
    @Override
    public void endDocument() throws SAXException {
        System.out.println("文档结束");
    }

    List> getList() {
        return list;
    }

}

3. 测试方法

public static void get() throws Exception {
        String driver = "com.mysql.cj.jdbc.Driver";
        String url = "jdbc:mysql://192.168.0.199:3306/zkxausi?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&serverTimezone=UTC&useSSL=false" ;
        String user = "root";
        String password = "Zkxa~123";
        Connection conn = null;
        Statement stmt = null;
        Class.forName(driver);
        conn = DriverManager.getConnection(url, user, password);
        stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);

        ResultSet result = stmt.executeQuery("SELECT * FROM t_security_user");
      String filePath = "E://user.xml";
        XmlUtils.resultSet2XML(result,filePath);
        System.out.println("===========================华丽的分割线===============================");
        XmlUtils.XML2Sql(filePath);

    }

4. 测试结果




20
rthr
$2a$10$SH9nQnfjK7bEPG.fnoOdt/VyG
1
1
2
152.168.0.111
管理员


123456
[email protected]
1.0.0.0
254.254.254.254
00:00
23:59
1
0

1
刚刚
3

2021-03-30 14:36:32

2021-12-29 09:27:32


59
洱海天域
$2a$10$KIcMWVYgR5yOdynajUcr3.Zpm
3
1
2
152.168.0.146
人事
NBMsyGCTvpGcosR783Ys79gnfvq4dy3Jg8Dm9sey15lQrp//7dxOo8wENb+nAATgCyo1eg6f2WXO2fLjO3Jg3xR2rXxdmQy1/C0H5kwGkx9/QjdUgxLdih/fsZwxB8M1aK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QWcfziqEiPYhziiX/j0m20JRXcTK8bKlNd+dMqkTdtURUcUKJEOQyNkJEUoXljHkTE/v74/U5U9y5Yn/3ZtShNcbn
82728A277D598757


152.168.0.146
152.168.0.146
00:00
23:59
1
32
团日活动被淘汰你也见一面人的




2021-12-27 16:15:34

2021-12-29 09:27:32

你可能感兴趣的:(数据库,数据库,xml)