美文网首页
Java读取MySQL表中的信息并生成表格

Java读取MySQL表中的信息并生成表格

作者: lizhencheng | 来源:发表于2019-03-16 17:44 被阅读0次

    前言

    每次写报告都需要写数据库设计,然后就需要以表格的形式说明每张表中的字段、字段类型等信息,如果表和表的字段很少,直接人工画表格很快就做完了,但是如果表很多并且每张表的字段也很多,那么人工画表格就会需要非常多的时间。因此,记录一下如何使用Java读取MySQL表中的信息并生成表格。

    依赖

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.47</version>
    </dependency>
    
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>ooxml-schemas</artifactId>
        <version>1.1</version>
    </dependency>
    <dependency>
        <groupId>fr.opensagres.xdocreport</groupId>
        <artifactId>org.apache.poi.xwpf.converter.core</artifactId>
        <version>1.0.6</version>
    </dependency>
    

    代码实现

    public class SqlTable {
        // JDBC 驱动名及数据库 URL
        static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
        static final String DATABASE = "mall"; // 数据库名
        static final String DB_URL = "jdbc:mysql://localhost:3306/" + DATABASE;
    
        // 数据库的用户名与密码,需要根据自己的设置
        static final String USER = "root";
        static final String PASS = "root";
    
        public static void main(String[] args) throws IOException {
            // 例如需要数据库中address、merchant这两张表的信息
            sqlTable2WorldTable(new String[]{"address","merchant"});
        }
    
        /**
         *
         * @param tableNames 传入一个字符串数组
         */
        public static void sqlTable2WorldTable(String[] tableNames) {
            Connection conn = null;
            Statement stmt = null;
            try{
                // 注册 JDBC 驱动
                Class.forName("com.mysql.jdbc.Driver");
                // 打开链接
                System.out.println("连接数据库...");
                conn = DriverManager.getConnection(DB_URL,USER,PASS);
                // 执行查询
                System.out.println(" 实例化Statement对象...");
                stmt = conn.createStatement();
                ResultSet rs = null;
    
    
                //Blank Document
                XWPFDocument document= new XWPFDocument();
                //Write the Document in file system
                FileOutputStream out = new FileOutputStream(new File("create_table.docx"));
                for (int i = 0; i < tableNames.length; i++) {
                    // 获取表注释
                    String getTableCommentSql = "SELECT table_name,table_comment FROM information_schema.TABLES WHERE table_schema = '" + DATABASE + "'and table_name = '" + tableNames[i] + "'";
                    rs = stmt.executeQuery(getTableCommentSql);
                    rs.next();
                    String table_comment = rs.getString("table_comment");
                    String table_name = rs.getString("table_name");
                    //添加标题
                    XWPFParagraph titleParagraph = document.createParagraph();
                    //设置段落居中
                    titleParagraph.setAlignment(ParagraphAlignment.CENTER);
                    XWPFRun titleParagraphRun = titleParagraph.createRun();
                    titleParagraphRun.setText(table_name + "(" + table_comment + ")");
                    titleParagraphRun.setColor("000000");
    
                    //基本信息表格
                    XWPFTable infoTable = document.createTable();
                    //列宽自动分割
                    CTTblWidth infoTableWidth = infoTable.getCTTbl().addNewTblPr().addNewTblW();
                    infoTableWidth.setType(STTblWidth.DXA);
                    infoTableWidth.setW(BigInteger.valueOf(9072));
    
                    //表格第一行
                    XWPFTableRow infoTableRowOne = infoTable.getRow(0);
                    infoTableRowOne.getCell(0).setText("字段名");
                    infoTableRowOne.addNewTableCell().setText("类型");
                    infoTableRowOne.addNewTableCell().setText("默认值");
                    infoTableRowOne.addNewTableCell().setText("键");
                    infoTableRowOne.addNewTableCell().setText("是否为空");
                    infoTableRowOne.addNewTableCell().setText("注释");
    
                    // 获取表字段
                    String getColumnSql = "select COLUMN_NAME,COLUMN_TYPE,COLUMN_DEFAULT,IS_NULLABLE,COLUMN_KEY,COLUMN_COMMENT from information_schema.COLUMNS where table_name = '" + tableNames[i] + "'";
                    rs = stmt.executeQuery(getColumnSql);
                    // 展开结果集数据库
                    while(rs.next()){
                        // 通过字段检索
                        String COLUMN_NAME  = rs.getString("COLUMN_NAME");
                        String COLUMN_TYPE = rs.getString("COLUMN_TYPE");
                        String COLUMN_DEFAULT = rs.getString("COLUMN_DEFAULT");
                        String COLUMN_KEY = rs.getString("COLUMN_KEY");
                        String COLUMN_COMMENT = rs.getString("COLUMN_COMMENT");
                        String IS_NULLABLE = rs.getString("IS_NULLABLE");
    
                        XWPFTableRow infoTableRow = infoTable.createRow();
                        infoTableRow.getCell(0).setText(COLUMN_NAME);
                        infoTableRow.getCell(1).setText(COLUMN_TYPE);
                        infoTableRow.getCell(2).setText(COLUMN_DEFAULT);
                        infoTableRow.getCell(3).setText(COLUMN_KEY);
                        infoTableRow.getCell(4).setText(IS_NULLABLE);
                        infoTableRow.getCell(5).setText(COLUMN_COMMENT);
                    }
                    XWPFParagraph paragraph = document.createParagraph();
                    XWPFRun paragraphRun = paragraph.createRun();
                    paragraphRun.setText("\r");
                }
                // 完成后关闭
                rs.close();
                stmt.close();
                conn.close();
    
                document.write(out);
                out.close();
            }catch(SQLException se){
                // 处理 JDBC 错误
                se.printStackTrace();
            }catch(Exception e){
                // 处理 Class.forName 错误
                e.printStackTrace();
            }finally{
                // 关闭资源
                try{
                    if(stmt!=null) stmt.close();
                }catch(SQLException se2){
                }// 什么都不做
                try{
                    if(conn!=null) conn.close();
                }catch(SQLException se){
                    se.printStackTrace();
                }
            }
            System.out.println("完成!");
        }
    }
    

    运行结果

    https://img.haomeiwen.com/i7378112/ee70f75ed2834e56.png

    相关文章

      网友评论

          本文标题:Java读取MySQL表中的信息并生成表格

          本文链接:https://www.haomeiwen.com/subject/nhmsmqtx.html