mysql导出某个库所有表名和表名的注释并保存在excel

import java.io.File;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

public class ExportMysqlSchema {

    public static void main(String[] args) throws Exception {
        // 连接mysql数据库
        String url = "jdbc:mysql://localhost:3306/test?user=root&password=root";
        Connection conn = DriverManager.getConnection(url);
        Statement stmt = conn.createStatement();

        // 获取某个库所有表名和表名的注释
        String sql = "SELECT TABLE_NAME, TABLE_COMMENT FROM information_schema.TABLES WHERE TABLE_SCHEMA='test'";
        ResultSet rs = stmt.executeQuery(sql);

        // 创建excel文件
        File file = new File("mysql_schema.xls");
        FileOutputStream fos = new FileOutputStream(file);

        // 创建excel工作簿
        Workbook workbook = new HSSFWorkbook();
        // 创建excel工作表
        Sheet sheet = workbook.createSheet("test");
        // 创建excel表头
        Row header = sheet.createRow(0);
        header.createCell(0).setCellValue("TABLE_NAME");
        header.createCell(1).setCellValue("TABLE_COMMENT");

        // 写入excel数据
        int index = 1; // 行索引
        while (rs.next()) {
            // 获取表名和表名的注释
            String tableName = rs.getString(1);
            String tableComment = rs.getString(2);
            // 创建excel行
            Row row = sheet.createRow(index++);
            // 写入excel单元格
            row.createCell(0).setCellValue(tableName);
            row.createCell(1).setCellValue(tableComment);
        }

        // 保存excel文件
        workbook.write(fos);

        // 关闭资源
        fos.close();
        workbook.close();
        rs.close();
        stmt.close();
        conn.close();
    }
}

关注公众号“大模型全栈程序员”回复“小程序”获取1000个小程序打包源码。更多免费资源在http://www.gitweixin.com/?p=2627

发表评论

邮箱地址不会被公开。 必填项已用*标注