使用java + jdbc连接数据库,并解析成XML格式的文件。。另外有对流文件的操作。。(数据迁移)

说明:迁移别人旧系统数据库数据时,临时用到的,就写了一个java应用程序。很多小细节没有处理,但是可以正常使用。。如果要运行大数据量的话估计要好好认真的处理下文件流的资源关闭,否则小心内存溢出。。。 

 

目录说明:

一、代码

二、配置文件

三、运行方式

四、效果展示

五、注意事项 - jdk版本问题

 

 

一、代码

import org.w3c.dom.CDATASection;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 将SQL SERVER中查询到的记录转换成Xml格式的数据,并将对应的附件信息归到一个文件夹下
 *
 * @date 2019/05/18
 * @author linrui
 * */
public class SelectToXml {

    /**
     *  程序入口
     * */
    public static void main(String[] args) {
        Connection connection = getConnection();
        System.out.println("数据库连接成功!");
        Statement statement = null;
        ResultSet rs = null;
        try {
            statement = connection.createStatement();
            String sql = getSelectSQL();
            rs = statement.executeQuery(sql);
        } catch (SQLException e) {
            System.out.println("操作数据库异常!");
            e.printStackTrace();
        }

        //生成xml,并返回生成的条数
        try {
            long count = createXml(rs);
            System.out.println("生成了" + count + "条xml数据!");
        } catch (Exception e) {
            System.out.println("生成xml过程中出现了未知的异常!");
            e.printStackTrace();
        }

        //关闭资源
        closeAll(connection, statement);
    }

    /**
     * 生成xml,并返回生成的条数
     *
     * @param rs 数据库查询结果集
     * @return int 返回生成xml的条数
     * */
    private static long createXml(ResultSet rs) throws Exception {
        // 创建解析器工厂
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = factory.newDocumentBuilder();

        //查询到多少条记录,就生成多少份xml
        long count = 0;
        while (rs.next()) {
            count ++;
            Document document = db.newDocument();
            document.setXmlVersion("1.0");
            document.setXmlStandalone(true);

            Element docs = document.createElement("docs");
            // 向docs根节点中添加子节点doc
            Element doc = document.createElement("doc");
            doc.setAttribute("uuid",rs.getString("ID"));

            //每个字段信息
            //原文ID
            Element item = document.createElement("item");
            item.setAttribute("name", "RESOURCE_ID");
            CDATASection cdataSection = document.createCDATASection(rs.getString("ID"));
            item.appendChild(cdataSection);
            doc.appendChild(item);

            //创建一个新的目录
            File file = new File(getNewFilePath());
            file.mkdir();
            file = new File(getNewFilePath() + rs.getString("ID"));
            file.mkdir();

            //文件标题
            item = document.createElement("item");
            item.setAttribute("name", "TITLE");
            cdataSection = document.createCDATASection(rs.getString("WSBT"));
            item.appendChild(cdataSection);
            doc.appendChild(item);

            //处理关联的附件
            if (rs.getString("FJID") != null && rs.getString("FJID") != "") {
                selectRelationFiles(rs.getString("ID"), rs.getString("FJID"));
            }

            //处理正文
            InputStream in = rs.getBinaryStream("FWWJ");
//            String strFile = getNewFilePath()+ rs.getString("ID") + "\\我是正文"+".txt";
            String strFile = "D:\\" + "我是正文" + count;
            OutputStream out = new FileOutputStream(strFile);
            byte[] bytes = new byte[1024];
            while(in.read(bytes,0,1024) != -1){
                out.write(bytes);
            }

            out.close();
            in.close();


            // 将doc节点添加到docs根节点中
            docs.appendChild(doc);
            // 将docs节点(已包含doc)添加到dom树中
            document.appendChild(docs);

            // 创建TransformerFactory对象
            TransformerFactory tff = TransformerFactory.newInstance();
            // 创建 Transformer对象
            Transformer tf = tff.newTransformer();

            // 输出内容是否使用换行
            tf.setOutputProperty(OutputKeys.INDENT, "yes");
            // 创建xml文件并写入内容
            tf.transform(new DOMSource(document), new StreamResult(new File(getNewFilePath() + rs.getString("ID") + "\\basicInfo" +".xml")));
        }

        return count;
    }

    /**
     * 查询与发文相关联的附件
     * */
    private static void selectRelationFiles(String sourceId, String fjid) {
        Connection connection = getConnection();
        PreparedStatement preparedStatement;
        ResultSet rs;
        try {
            String sql = "select * from dbo.TS_COMMON_YWXX where ywzid=?";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1, Integer.valueOf(fjid).intValue());
            rs = preparedStatement.executeQuery();

            while (rs.next()) {
                //读取文件
                String filePath = getSqlServerFilePath();
                filePath += rs.getString("XYWM");
                InputStream in = new FileInputStream(filePath);

                //写入新的文件
                String strFile = getNewFilePath()+ sourceId + "\\" + rs.getString("JYWM")+rs.getString("WJKZM");
                OutputStream out = new FileOutputStream(strFile);
                byte[] bytes = new byte[1024];
                while(in.read(bytes,0,1024) != -1){
                    out.write(bytes);
                }
            }
        } catch (SQLException e) {
            System.out.println("查询附件时,操作数据库异常!");
            e.printStackTrace();
            throw new RuntimeException();
        } catch (FileNotFoundException e) {
            System.out.println("读写附件时,文件未找到异常!");
            e.printStackTrace();
            throw new RuntimeException();
        } catch (IOException e) {
            System.out.println("写附件时,遇到未知错误!");
            e.printStackTrace();
            throw new RuntimeException();
        }

    }

    /**
     * 获取Connection连接
     *
     * @return connection
     * */
    private static Connection getConnection () {
        //获取指定的数据库连接信息
        Map<String, String> databaseMap =  getDatabaseMap();

        //声明Connection对象
        Connection con = null;
        //驱动程序名
        String driver = databaseMap.get("driverName");
        //URL指向要访问的数据库名
        String url = databaseMap.get("url");
        //MySQL配置时的用户名
        String userName = databaseMap.get("userName");
        //MySQL配置时的密码
        String password = databaseMap.get("password");

        try {
            //加载驱动程序
            Class.forName(driver);
            con = DriverManager.getConnection(url, userName, password);
        } catch(ClassNotFoundException e) {
            //数据库驱动类异常处理
            System.out.println("没有找到驱动!");
            e.printStackTrace();
            throw new RuntimeException();
        } catch(SQLException e) {
            //数据库连接失败异常处理
            System.out.println("连接失败!");
            e.printStackTrace();
            throw new RuntimeException();
        }catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
        return con;
    }

    /**
     * 获取数据库连接信息
     *
     * @return Map
     * */
    private static Map<String, String> getDatabaseMap() {
        Map<String, String> databaseMap = new HashMap<>(4);
        //读取属性文件
        Properties properties = readProperties();
        databaseMap.put("driverName", properties.getProperty("driverName"));
        databaseMap.put("url", properties.getProperty("url"));
        databaseMap.put("userName", properties.getProperty("userName"));
        databaseMap.put("password", properties.getProperty("password"));

        return databaseMap;
    }

    /**
     * 获取SQL语句
     *
     * @return String
     * */
    private static String getSelectSQL() {
        Properties properties = readProperties();
        return properties.getProperty("selectSQL");
    }

    /**
     * 获取源文件路径
     *
     * @return String
     * */
    private static String getSqlServerFilePath() {
        Properties properties = readProperties();
        return properties.getProperty("sqlServerFilePath");
    }

    /**
     * 获取存放文件的路径
     *
     * @return String
     * */
    private static String getNewFilePath() {
        Properties properties = readProperties();
        return properties.getProperty("newFilePath");
    }

    /**
     * 读取属性文件
     *
     * @return Properties
     * */
    private static Properties readProperties() {
        InputStream inputStream;
        Properties properties = null;

        try {
            //用流读入properties配置文件
            inputStream = new FileInputStream("D:\\database.properties");
            properties = new Properties();
            //从输入字节流读取属性列表(键和元素对)
            properties.load(inputStream);
            //用此属性列表中指定的键搜索属性,获取驱动,url,username,password
//            System.out.println("数据库驱动名称:" + properties.getProperty("driverName"));
//            System.out.println("数据库连接url:" + properties.getProperty("url"));
//            System.out.println("数据库连接userName:" + properties.getProperty("userName"));
//            System.out.println("数据库连接password:" + properties.getProperty("password"));
//            System.out.println("数据库查询语句selectSQL:" + properties.getProperty("selectSQL"));
//            System.out.println("文件路径sqlServerFilePath:" + properties.getProperty("sqlServerFilePath"));
//            System.out.println("新的存放文件的路径newFilePath:" + properties.getProperty("newFilePath"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (properties == null) {
            System.out.println("读取属性文件失败,值为null");
            throw new RuntimeException();
        }

        return properties;
    }

    /**
     * 关闭资源
     *
     * @param conn 数据库连接
     * @param statement 执行数据库操作的对象
     * */
    private static void closeAll(Connection conn, Statement statement){
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                System.out.println("关闭statement资源失败");
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                System.out.println("关闭数据库连接connection失败");
            }
        }
    }
}

二、配置文件 database.properties

driverName=com.microsoft.sqlserver.jdbc.SQLServerDriver
url=jdbc:sqlserver://localhost:1433;DatabaseName=OA2015
userName=sa
password=123
selectSQL=select * from dbo.OT_SENDFILE
sqlServerFilePath=D:\\sqlServerFileTest\\
newFilePath=D:\\newSqlServiceFile\\

三、运行环境

关于运行环境:(只需要有java的运行环境即可,有下面两种方式)

1. 第一种方式,直接用idea打成jar包运行。

①打成jar包之后

②打开cmd,到这个路径下,然后运行 java -jar SqlServerSelectToXml.jar  即可。

2.第二种方式,直接运行.class 文件(这里我还是用idea工具,编译后找到对应的.class文件即可)

①找到.class文件

②打开cmd,同样是进到.class文件所在的目录(可以不用跟依赖的jar包放在一个目录下)。

然后运行命令java -cp .;D:\sqljdbc4.jar SelectToXml 即可。这里注意,要配置java的环境变量,不然这里的 ‘ .; ’会识别不到当前路径。

 

四、效果

1.xml

2.文件

 

五、jdk版本问题

别人的旧系统是jdk5,然后我自己是jdk8 。这是个蛋疼的问题,于是直接在别人旧系统上装了个jdk8就好了。

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章