在开发当中不少场景需要把MySQL数据库中所有表名和表名注释导出到Excel表格中。
具体操作步骤如下:
1、连接MySQL数据库
首先,通过JDBC驱动程序连接到MySQL数据库,并设置连接地址、用户名和密码。
2、获取库中所有表名和表名注释
使用SQL语句查询指定库中的表名和表名注释,返回一个ResultSet结果集。
3、创建Excel文件、工作簿、工作表和表头
创建FileOutputStream对象并指定文件保存路径,创建HSSFWorkbook对象作为工作簿,创建工作表并命名,然后创建表头行并插入两个单元格作为列名。
4、写入Excel数据
遍历ResultSet结果集中的所有数据行,获取每行的表名和表名注释,然后创建行和单元格,将数据写入Excel表格中。
5、保存Excel文件
将工作簿对象写入FileOutputStream对象中,将数据写入Excel表格中,然后关闭相关资源。
6、关闭资源
关闭FileOutputStream对象、工作簿对象、结果集对象、Statement对象和Connection对象。
参考代码:
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();
}
}
在开发当中不少场景需要把MySQL数据库中所有表名和表名注释导出到Excel表格中。




