读取mysql数据库表结构生成接口文档

1、引入依赖

<!-- 导出word -->
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.30</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/e-iceblue/spire.doc.free -->
        <dependency>
            <groupId>e-iceblue</groupId>
            <artifactId>spire.doc.free</artifactId>
            <version>2.7.3</version>
        </dependency>
    <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.7.20</version>
        </dependency>
 <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.22</version>
        </dependency>

3、工具类ApiDoc

package com.example.rediscache.utils;

import com.baomidou.mybatisplus.core.toolkit.ExceptionUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;

import java.io.*;
import java.util.Map;

public class ApiDoc {

    public static final String MAC = "Mac";
    /**
     * Windows
     */
    public static final String WINDOWS = "Windows";
    public static Logger log = LoggerFactory.getLogger(ApiDoc.class);

    /**
     * 将数据导入word模板生成word
     *
     * @param params 数据
     * @return docx临时文件的全路径
     * @throws IOException
     */
    public static String createWord(Map<String, Object> params) throws IOException {
        String templateFile = "api.doc.ftl";
        String filePath = "D://html";
        File file = null, templateFile1 = null;
        FileOutputStream fileOutputStream = null;
        Writer out = null;
        InputStream inputStream = null;
        try {
            File file1 = new File(filePath);
            //指定模板存放位置
            ClassPathResource tempFileResource = new ClassPathResource(templateFile);
            //创建临时文件
            file = File.createTempFile("接口文档-", ".docx", file1);
            //得到临时文件全路径  ,作为word生成的输出全路径使用
            String outputDir = file.getAbsolutePath();
            log.info("创建临时文件的路径为:{}", outputDir);

            //创建模板临时文件
            templateFile1 = File.createTempFile(templateFile, ".xml", file1);
            fileOutputStream = new FileOutputStream(templateFile1);
            inputStream = tempFileResource.getInputStream();
            IOUtils.copy(inputStream, fileOutputStream);
            //得到临时模板文件全路径
            String templateFilePath = templateFile1.getAbsolutePath();
            log.info("创建临时文件的路径为:{}", templateFilePath);

//           new ClassPathResource("aaa").getInputStream().close();
            // 设置FreeMarker的版本和编码格式
            Configuration configuration = new Configuration();
            configuration.setDefaultEncoding("UTF-8");
            // 设置FreeMarker生成Word文档所需要的模板的路径
            configuration.setDirectoryForTemplateLoading(templateFile1.getParentFile());
            // 设置FreeMarker生成Word文档所需要的模板
            Template t = configuration.getTemplate(templateFile1.getName(), "UTF-8");

            // 创建一个Word文档的输出流
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(outputDir)), "UTF-8"));
            //FreeMarker使用Word模板和数据生成Word文档
            t.process(params, out); //将填充数据填入模板文件并输出到目标文件
        } catch (Exception e) {
            log.error("word生成报错,错误信息{}", e.getMessage());
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.flush();
                out.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
            if (fileOutputStream != null) {
                fileOutputStream.close();
            }
            if (templateFile1 != null) {
                templateFile1.delete();
            }
        }
        try {
            //获取系统信息
            String osName = System.getProperty("os.name");
            if (osName != null) {
                if (osName.contains(MAC)) {
                    Runtime.getRuntime().exec("open " + file.getAbsolutePath());
                } else if (osName.contains(WINDOWS)) {
                    Runtime.getRuntime().exec("cmd /c start " + file.getAbsolutePath());
                }
            }
        } catch (IOException e) {
            throw ExceptionUtils.mpe(e);
        }
        return file == null ? null : file.getAbsolutePath();
    }


}

4、编写测试方法

package com.example.rediscache;

import com.example.rediscache.utils.ApiDoc;
import org.junit.platform.commons.util.StringUtils;

import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MysqlCreateApiDoc {

    //读取数据库生成接口文档
    public static void main(String[] args) {
        String database = "ry-cloud";
        String url = String.format("jdbc:mysql://localhost:3306/%s?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false&serverTimezone=UTC", database);
        String username = "root";
        String password = "pyrx123";
        List<HashMap<String, Object>> list = new ArrayList<>();
        try {
            Connection conn = DriverManager.getConnection(url, username, password);
            Statement stmt = conn.createStatement();
            ResultSet tables = stmt.executeQuery(String.format("SELECT table_name, table_comment " + "FROM information_schema.tables WHERE table_schema = '%s'", database));
            while (tables.next()) {
                String tableName = tables.getString("table_name");
                String table_comment = tables.getString("table_comment");
                System.out.println("Table: " + tableName + "---table_comment: " + table_comment);
                PreparedStatement ps = conn.prepareStatement("show full columns from " + tableName);
                ResultSet c = ps.executeQuery();
                HashMap<String, Object> map = new HashMap<>();
                //模块名称
                if (StringUtils.isBlank(table_comment)) {
                    map.put("model_name", toCamelCase(tableName));
                } else {
                    map.put("model_name", table_comment.replace("表", ""));
                }
                map.put("requestUrl", "/" + toCamelCase(tableName));
                List<HashMap<String, String>> paramslist = new ArrayList<>();
                while (c.next()) {
                    System.out.println("字段名:" + c.getString("Field") + "------" + "类型:" + convert(c.getString("Type")) + "------" + "备注: " + c.getString("Comment") + "------" + "是否必选: " + c.getString("Null"));
                    String Null = c.getString("Null").contains("YES") ? "是" : "否";
                    HashMap<String, String> methodParams = new HashMap<>();
                    methodParams.put("FILENAME", toCamelCase(c.getString("Field")));
                    methodParams.put("FILEType", convert(c.getString("Type")));
                    methodParams.put("Null", Null);
                    methodParams.put("FILEDESC", c.getString("Comment"));
                    paramslist.add(methodParams);
                }
                map.put("paramslist", paramslist);
                map.put("resultslist", paramslist);
                list.add(map);
            }
            conn.close();
            stmt.close();
            int length = list.size();
            for (int i = 0; i < length; i += 7) {
                // 处理子列表,例如打印出来
                Map<String, Object> params = new HashMap<>();
                params.put("tmp_title", "远程智能巡视");
                params.put("apilist", list.subList(i, Math.min(length, i + 7)));//告警点位汇总
                new ApiDoc().createWord(params);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static String convert(String fieldType) {
        if (fieldType.contains("varchar") || fieldType.contains("text")) {
            return "String";
        } else if (fieldType.contains("int")) {
            return "Integer";
        } else if (fieldType.contains("boolean") || fieldType.contains("char")) {
            return "Boolean";
        } else if (fieldType.contains("date") || fieldType.contains("time")) {
            return "Date";
        } else if (fieldType.contains("decimal") || fieldType.contains("double") || fieldType.contains("float")) {
            return "Double";
        }
        return "Object";
    }

    //下划线转驼峰
    public static String toCamelCase(CharSequence name) {
        if (null == name) {
            return null;
        }
        String name2 = name.toString();
        if (name2.contains("_")) {
            StringBuilder sb = new StringBuilder(name2.length());
            boolean upperCase = false;
            for (int i = 0; i < name2.length(); ++i) {
                char c = name2.charAt(i);
                if (c == '_') {
                    upperCase = true;
                } else if (upperCase) {
                    sb.append(Character.toUpperCase(c));
                    upperCase = false;
                } else {
                    sb.append(Character.toLowerCase(c));
                }
            }
            return sb.toString();
        }
        return name2;
    }

}

5、resources 目录下存放api.doc.ftl 模版文件,点击下载可得

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 要将MySQL结构导出为Excel,你可以按照以下步骤进行: 1. 使用MySQL命令行工具或可视化工具,连接到你的MySQL数据库。 2. 运行SHOW TABLES;语句,以获取数据库中所有的列。 3. 针对每个,运行SHOW CREATE TABLE table_name;语句,以获取的创建语句。将结果复制到一个文本编辑器中,以备后用。 4. 打开Microsoft Excel(或任何其他支持Excel格式的电子格应用程序)。 5. 在第一个工作中,将名称和结构导入。你可以使用格来组织这些信息,其中每个的名称位于第一个单元格,结构的列名和数据类型位于第二行开始的单元格。 6. 在第二个工作中,将每个的列信息导入。你可以使用格来组织这些信息,其中每个列名和相关属性位于第一行开始的单元格。 7. 将第一个工作和第二个工作保存为Excel文件。 通过按照上述步骤操作,你可以将MySQL结构导出为Excel文件。这样,你就可以轻松地查看和共享结构信息了。 ### 回答2: 要将 MySQL 结构导出为 Excel 文件,可以采用以下步骤: 1. 使用 MySQL 的 "DESCRIBE" 命令或 "SHOW COLUMNS" 命令,查询结构信息。例如,可以执行以下 SQL 语句获取 "table_name" 的结构信息: ```sql DESCRIBE table_name; ``` 或者 ```sql SHOW COLUMNS FROM table_name; ``` 2. 将查询结果保存为文本文件,例如 "table_structure.txt"。 3. 使用编程语言(如 Python、Java 等)读取文本文件中的数据,并将数据写入到 Excel 文件中。常用的库包括 openpyxl、XlsxWriter、Pandas 等。以下是使用 Python 的 openpyxl 库的示例代码: ```python from openpyxl import Workbook # 创建一个新的 Excel 文档 workbook = Workbook() sheet = workbook.active # 读取结构信息的文本文件 with open('table_structure.txt', 'r') as f: lines = f.readlines() # 逐行写入 Excel 文件 for i, line in enumerate(lines): columns = line.strip().split('\t') # 假设每一行的字段以制符分隔 for j, column in enumerate(columns): sheet.cell(row=i+1, column=j+1).value = column workbook.save('table_structure.xlsx') # 保存 Excel 文件 ``` 4. 运行以上代码后,会生成一个名为 "table_structure.xlsx" 的 Excel 文件,其中包含了 MySQL 结构信息。 需要注意的是,导出的 Excel 文件中可能不包含部分特殊字符或格式,例如注释、默认值等。因此,在实际应用中,可能需要根据具体需求进行进一步的处理和调整。 ### 回答3: 要将MySQL结构导出为Excel,可以按照以下步骤进行操作: 第一步,使用数据库管理工具,例如Navicat for MySQL或phpMyAdmin等,连接到MySQL数据库。 第二步,选择要导出结构数据库,然后选择要导出结构的数据。 第三步,右键点击选择的,然后选择“导出”选项。 第四步,在导出设置中,选择导出格式为CSV或Excel(XLS或XLSX)。 第五步,选择导出路径和文件名,点击“导出”按钮。 第六步,等待导出过程完成。 通过以上步骤,可以将MySQL结构导出为Excel文件。这样导出的Excel文件中将包含的所有字段名称、数据类型、约束条件等结构信息。 另外,如果只需要导出的列名而不需要其他结构信息,可以通过编写SQL语句查询数据库的information_schema来获取列名,然后将结果导出到Excel文件中。例如,可以使用以下SQL语句查询的列名: SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '数据库名' AND TABLE_NAME = '名'; 然后将查询结果复制到Excel文件中即可。这种方法更加简单,适用于只需要导出的列名的情况。 总结起来,通过数据库管理工具导出整个结构信息,或者通过编写SQL语句查询的列名,然后将结果导出到Excel文件中,都可以实现将MySQL结构导出为Excel的操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值