生成yaml

57 阅读1分钟

最终格式

intercept:
  table:
    t_amzdb_distributor_calc_data_v2: t_amzdb_distributor_calc_data_v2
    t_amadb_sign_company: t_amadb_sign_company
    t_amzdb_post_mapper: t_amzdb_post_mapper
    t_amadb_seller_monitor_feedback_day: t_amadb_seller_monitor_feedback_day
    t_amz_bak_product_info: t_amz_bak_product_info

代码

public class DatabaseTablesToYml {

    public static void main(String[] args) {
        Connection conn = null;
        ResultSet rs = null;
        try {

            // 2. 创建数据库连接,替换为实际的数据库URL、用户名和密码
            conn = DriverManager.getConnection("jdbc:mysql://xxxx:3306/xxxx"
                    , "xx", "xxx");

            // 3. 执行SQL查询获取所有表名
            Statement stmt = conn.createStatement();
            String sql = "SHOW TABLES";
            rs = stmt.executeQuery(sql);

            // 4. 构建YAML数据结构
            Map<String, Map> yamlMap = new HashMap<>();
            yamlMap.put("intercept", new HashMap<>());
            Map<String, String> tableMap = new HashMap<>();
            yamlMap.get("intercept").put("table", tableMap);

            // 5. 将表名添加到YAML结构中
            while (rs.next()) {
                String tableName = rs.getString(1);
                tableMap.put(tableName, tableName);
            }

            //这一行设置了默认的节点流样式为 `BLOCK`。在SnakeYAML中,`FlowStyle` 有两种可能的取值:

            -   `FLOW`:紧凑流式风格,适合于将多个数据项挤在同一行内,常用于小型结构或者为了节省空间。
            -   `BLOCK`:块状流式风格,每个数据项独占一行,增加了可读性,通常用于较大的数据结构或需要清晰视觉分隔的情况。

            当设置为 `BLOCK` 时,生成的YAML文件将会以多行形式展现数据结构,每一对键值对会换行展示,并且带有适当的缩进。
            DumperOptions dumperOptions = new DumperOptions();
            dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
            Yaml yaml = new Yaml(dumperOptions);
            // 6. 将YAML数据写入文件
            yaml.dump(yamlMap, new FileWriter("database_tables.yml"));

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (rs != null) rs.close();
                if (conn != null) conn.close();
            } catch (SQLException se) {
                se.printStackTrace();
            }
        }
    }
}