從數據庫導出xml文件

原作者:Kevin12
出處: http://kevin12.iteye.com/blog/1940281

一、需要一個類來對應我們想導出的數據庫中的一個表

@Entity
@Table(name = "student_test")
public class StudentTest {

    private int number;

    private String name;

    private String major;


    @Column(columnDefinition= "int(10)", name = "NUMBER")
    public int getNumber(){
        return number;
    }
    public void setNumber(int number){
        this.number=number;
    }

    @Column(columnDefinition= "varchar(255)", name = "NAME")
    public String getName(){
        return name;
    }
    public void setName(String name){
        this.name=name;
    }

    @Column(columnDefinition= "varchar(255)", name = "MAJOR")
    public String getMajor(){
        return major;
    }
    public void setMajor(String major){
        this.major=major;
    }
}

二、需要有一個java連接mysql的類

public class DBDao {
    private static String USER = "USERNAME";
    private static String PASSWORD = "PASSWORD";
    private static String DB_URL = "jdbc:mysql://IP ADDRESS:PORT/DB NAME";
    private static String DB_DRIVER = "com.mysql.jdbc.Driver";
    private static Connection connection = null;

    //連接數據庫
    public static Connection getConnection(){
        try {
            Class.forName(DB_DRIVER);
            connection = DriverManager.getConnection(DB_URL, USER, PASSWORD);
        } catch (Exception e) {
            System.out.println("數據庫連接異常");
            e.printStackTrace();
        }
        return connection;
    }

    //關閉數據庫連接
    public  static void closeConnection(Connection connection){
        if(connection != null){
            try {
                connection.close(); 
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
} 

三、需要有一個從數據庫讀取該實體表,並轉換成ArrayList對象的類

public class StudentListDao {
    private String SQL =""; 

    public List<StudentTest> getStudentTests(){
        List<StudentTest> studentTests = new ArrayList<>();
        SQL = "select * from student_test";
        Connection connection = null;
        PreparedStatement pstmt = null;
        try {
            connection = DBDao.getConnection();
            pstmt = (PreparedStatement) connection.prepareStatement(SQL);
            ResultSet rSet = (ResultSet) pstmt.executeQuery();//得到數據庫的查詢結果,一個數據集

            //判斷結果集是否有效
            while(rSet.next()){
                StudentTest studentTest = new StudentTest();
                studentTest.setNumber((Integer.parseInt(rSet.getString("number"))));
                studentTest.setName(rSet.getString("name"));
                studentTest.setMajor(rSet.getString("major"));
                studentTests.add(studentTest);
            }
            connection.close();
            pstmt.close();
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            DBDao.closeConnection(connection);
        }
        return studentTests;
    }
}

這裏我碰見了一個問題是之前寫成了if(rSet.next()),然後在set和add的時候,發現是添加了第二個數據。解決方法是改成while(rSet.next()),判斷下一個是否爲空,不爲空就添加這一個。

四、需要用一個方法把對象按規定格式寫到xml文件中

    /** 
     * @Description:將對應的對象寫到xml中  
     */  
    public static Element object2Element(Element root,Object obj,String id){  
        try {  
            //獲取Document根元素  
            Class clazz = obj.getClass();  
            //獲取對象名稱  
            String str = clazz.getName();  
            String objName = str.substring(str.lastIndexOf(".")+1);  
            //獲取對象元素(以表名爲標籤的元素),不存在,則創建  
            Element tableElement = root.element(objName);  
            if(tableElement == null){  
                tableElement = root.addElement(objName).addAttribute("id", id);  
            }  
            //創建一個節點元素  
            Element nodeElement = tableElement.addElement("node").addAttribute("id", id);  
            Field[] fields = clazz.getDeclaredFields();  
            //遍歷屬性  
            for(Field field :fields){  
                /**拼接出屬性對應的getter方法名*/  
                //獲取對象屬性  
                String fieldName = field.getName();  
                StringBuilder sb = new StringBuilder();  
                sb.append("get");  
                sb.append(fieldName.substring(0,1).toUpperCase());  
                if(fieldName.length()>1){  
                    sb.append(fieldName.substring(1));  
                }  
                String getMethodName = sb.toString();  
                //反射method對象  
                Method getMethod = obj.getClass().getMethod(getMethodName);  
                //調用方法獲取值  
                Object fieldValue = getMethod.invoke(obj);  
                //添加節點子元素元素  
                Element fieldElement = nodeElement.addElement(fieldName).addAttribute(fieldName, fieldName);  
                fieldElement.setText(fieldValue==null?"":fieldValue.toString());  
            }  
        } catch (Exception e) {  
            throw new RuntimeException(e);  
        }  
        return root;  
    }  

五、最後,寫一個方法來調用第四步寫的方法,並且導出xml文件吧

@Test  
    public void exportXML(){
        StudentListDao studentListDao = new StudentListDao();
        /**1.創建document*/  
        Document document = DocumentHelper.createDocument();  
        /**2.添加根元素*/  
        Element rootElement = document.addElement("root");  
        /**3.用反射將對象寫到xml中*/  
        List<StudentTest> list = studentListDao.getStudentTests();  
        for(StudentTest studentTest:list){  
            rootElement = TestXMLImport.object2Element(rootElement, studentTest, String.valueOf(studentTest.getNumber()));  
        }  
        /**4.將document寫到xml中並保存到服務器指定的目錄中*/  
        FileOutputStream xmlOut;  
        try {  
            xmlOut = new FileOutputStream(new File("G:/testXMLExport.xml"));  
            XMLWriter xmlWriter = new XMLWriter(xmlOut,OutputFormat.createPrettyPrint());  
            xmlWriter.write(document);  
            xmlWriter.close();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    } 

感謝原作者分享的方法!

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