使用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就好了。

 

 

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