写在前面:

因为工作时候经常遇到半路接手项目的情况,由于年代久远,数据库字典这块经常缺失。故写此篇,以便复用,也希望对大家有点帮助。

随笔内容不高级,如有不妥,不吝指正。

ps:有另一篇详细随笔可以参考【[功能集锦] 002 - mysql查询数据库字典+导出+样式一键整合至excel】。

------------------------------------------------------------分-割-线------------------------------------------------------------

以下为代码,只需要改动部分参数,就可以运行,生成excel文件。文件生成后,设置列宽自适应即可。

 import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Map;
import java.util.Set; import org.apache.commons.collections4.MapUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook; /**
* 生成数据库数据结构速查文件(数据库字典)
*
* @author ruran
* @since 2019年7月4日 下午3:25:13
*/
public class ProduceGuideOfDatabase { /*
* 数据来源
*
* SELECT pretab.TABLE_NAME AS 表名,pretab.TABLE_COMMENT AS 表释义,
* precol.COLUMN_NAME AS 字段名,precol.COLUMN_TYPE AS 字段类型,
* precol.COLUMN_DEFAULT AS 字段默认值,precol.COLUMN_COMMENT AS 表字段释义 FROM
* information_schema.`TABLES` AS pretab RIGHT JOIN
* information_schema.`COLUMNS` AS precol ON
* precol.TABLE_NAME=pretab.TABLE_NAME WHERE pretab.TABLE_SCHEMA ="此处填写库名"
* GROUP BY precol.TABLE_NAME,precol.COLUMN_NAME ORDER BY precol.TABLE_NAME;
*/
public static void main(String[] args) {
System.out.println("开始运行程序。。。");
long preTime = System.currentTimeMillis();
// 程序访问数据库拉取字典数据-程序整合成字典文件(配置数据库连接、要拉取得库名,一键运行代码即可)
reArrangeFromSQL();
System.out.println("运行完成,耗时:" + (System.currentTimeMillis() - preTime) + "ms");
} /**
* 直接从SQL中读取数据进行重整成excel
*
* @author ruran
* @since 2019年7月29日 下午7:41:50
*/
private static void reArrangeFromSQL() {
String ip = "xxxxxxxx", user = "xxxx", password = "xxxxxxxx", database = "information_schema";
Map<String, Map<String, TablePojo>> database_tables = new HashMap<>();
try {
String sqlStr = "SELECT pretab.TABLE_NAME AS 表名,pretab.TABLE_COMMENT AS 表释义,precol.COLUMN_NAME AS 字段名,precol.COLUMN_TYPE AS 字段类型, precol.COLUMN_DEFAULT AS 字段默认值,precol.COLUMN_COMMENT AS 表字段释义 FROM information_schema.`TABLES` AS pretab RIGHT JOIN information_schema.`COLUMNS` AS precol ON precol.TABLE_NAME=pretab.TABLE_NAME WHERE pretab.TABLE_SCHEMA =? GROUP BY precol.TABLE_NAME,precol.COLUMN_NAME ORDER BY precol.TABLE_NAME;";
Connection connection = getConnection(ip, user, password, database);
PreparedStatement pstmt = connection.prepareStatement(sqlStr);
ResultSet rs = null;
String[] databaseNames = "scrssit-scrssit2-scrssit3-scrssit4-scrssit5-scrssit6-scrssit7-scrssit8-scrssit9-scrssit10-scrssit11"
.split("-");
for (String databaseName : databaseNames) {
pstmt.setString(1, databaseName);
rs = pstmt.executeQuery();// 获取数据
String columnLines = "";
int countAll = 0;// 表总数
Map<String, TablePojo> tableNames = new HashMap<>();
String preTableName = "";
String preTableComment = "";
while (rs.next()) {
String currentTableName = isBlank(rs.getString(1)) ? "" : rs.getString(1);
if (tableNames.containsKey(getRealTablename(currentTableName))) {
continue;
}
String currentTableComment = isBlank(rs.getString(2)) ? "" : rs.getString(2);
String currentColumnName = isBlank(rs.getString(3)) ? "" : rs.getString(3);
String currentColumnType = isBlank(rs.getString(4)) ? "" : rs.getString(4);
String currentColumnDefault = isBlank(rs.getString(5)) ? "" : rs.getString(5);
String currentColumnComment = isBlank(rs.getString(6)) ? "" : rs.getString(6);
if (currentTableName.equals(preTableName)) {
columnLines += currentColumnName + "#" + currentColumnType + "#" + currentColumnDefault + "#"
+ currentColumnComment + "@";
continue;
}
if (countAll != 0 && !tableNames.containsKey(getRealTablename(preTableName))) {
TablePojo tablePojo = new TablePojo(preTableName, preTableComment, columnLines.substring(0,
columnLines.length() - 1));
tableNames.put(getRealTablename(preTableName), tablePojo);
}
countAll++;
columnLines = currentColumnName + "#" + currentColumnType + "#" + currentColumnDefault + "#"
+ currentColumnComment + "@";
preTableName = currentTableName;
preTableComment = currentTableComment;
}
// 最后一组数据判断+保存
if (!tableNames.containsKey(getRealTablename(preTableName))) {
TablePojo tablePojo = new TablePojo(preTableName, preTableComment, columnLines.substring(0,
columnLines.length() - 1));
tableNames.put(getRealTablename(preTableName), tablePojo);
}
database_tables.put(databaseName, tableNames);
}
rs.close();
pstmt.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
String url = "F:\\2-ME\\中心+部门\\1-scrs学习整理区\\";
String forFile = "系统数据库结构参考速查表-20190729.xlsx";
if (MapUtils.isNotEmpty(database_tables)) {
if (forFile.contains(".xlsx")) {
arrangeToXLSX(database_tables, url, forFile);
} else {
arrangeToXLS(database_tables, url, forFile);
}
}
} /**
* 取数据整合到excel-xls
*
* @author ruran
* @since 2019年7月23日 下午5:32:50
* @param tableNamesMap
* @param fos
*/
private static void arrangeToXLS(Map<String, Map<String, TablePojo>> database_tables, String url, String forFile) {
try (FileOutputStream fos = new FileOutputStream(url + forFile);) {
if (MapUtils.isNotEmpty(database_tables)) {
HSSFWorkbook currentWorkbook = new HSSFWorkbook();
// 获取所有样式
Map<String, CellStyle> cellStyles = getCellStyles(currentWorkbook);
Set<String> databaseNames = database_tables.keySet();
for (String databaseName : databaseNames) {
HSSFSheet currentSheet = currentWorkbook.createSheet(databaseName);
HSSFRow currentRow = null;
HSSFCell currentCell = null;
int rowIndex = -1;
Map<String, TablePojo> tableNames = database_tables.get(databaseName);
for (TablePojo tablePojo : tableNames.values()) {
// 空行
currentSheet.createRow(++rowIndex);
// 表头
currentRow = currentSheet.createRow(++rowIndex);
currentRow.setHeightInPoints(18);
currentCell = currentRow.createCell(0);
currentCell.setCellStyle(cellStyles.get("bluesStyle"));
currentCell.setCellValue(tablePojo.getTableName() + "(" + tablePojo.getTableComment() + ")");
CellRangeAddress region = new CellRangeAddress(rowIndex, rowIndex, 0, 3);
currentSheet.addMergedRegion(region);
// 表-标题栏
currentRow = currentSheet.createRow(++rowIndex);
currentRow.setHeightInPoints(18);
currentCell = currentRow.createCell(0);
currentCell.setCellStyle(cellStyles.get("blueStyle"));
currentCell.setCellValue("列名");
currentCell = currentRow.createCell(1);
currentCell.setCellStyle(cellStyles.get("blueStyle"));
currentCell.setCellValue("类型");
currentCell = currentRow.createCell(2);
currentCell.setCellStyle(cellStyles.get("blueStyle"));
currentCell.setCellValue("默认值");
currentCell = currentRow.createCell(3);
currentCell.setCellStyle(cellStyles.get("blueStyle"));
currentCell.setCellValue("释义");
// 表字段
String tableColumnsStr = tablePojo.getTableColumns();
for (String tableColumns : tableColumnsStr.split("@")) {
currentRow = currentSheet.createRow(++rowIndex);
currentRow.setHeightInPoints(18);
String[] tableColumnArr = tableColumns.split("#");
for (int i = 0; i < tableColumnArr.length; i++) {
currentCell = currentRow.createCell(i);
currentCell.setCellStyle(cellStyles.get("baseStyle"));
currentCell.setCellValue(tableColumnArr[i]);
}
}
}
}
currentWorkbook.write(fos);
}
} catch (Exception e) {
e.printStackTrace();
}
} /**
* 取数据整合到excel-xlsx
*
* @author ruran
* @since 2019年7月24日 上午11:51:56
* @param tableNamesMap
* @param fos
*/
private static void arrangeToXLSX(Map<String, Map<String, TablePojo>> database_tables, String url, String forFile) {
try (FileOutputStream fos = new FileOutputStream(url + forFile);) {
if (MapUtils.isNotEmpty(database_tables)) {
XSSFWorkbook currentWorkbook = new XSSFWorkbook();
// 获取所有样式
Map<String, CellStyle> cellStyles = getCellStyles(currentWorkbook);
Set<String> databaseNames = database_tables.keySet();
for (String databaseName : databaseNames) {
XSSFSheet currentSheet = currentWorkbook.createSheet(databaseName);
XSSFRow currentRow = null;
XSSFCell currentCell = null;
int rowIndex = -1;
Map<String, TablePojo> tableNames = database_tables.get(databaseName);
for (TablePojo tablePojo : tableNames.values()) {
// 空行
currentSheet.createRow(++rowIndex);
// 表头
currentRow = currentSheet.createRow(++rowIndex);
currentRow.setHeightInPoints(18);
currentCell = currentRow.createCell(0);
currentCell.setCellStyle(cellStyles.get("bluesStyle"));
currentCell.setCellValue(tablePojo.getTableName() + "(" + tablePojo.getTableComment() + ")");
CellRangeAddress region = new CellRangeAddress(rowIndex, rowIndex, 0, 3);
currentSheet.addMergedRegion(region);
// 表-标题栏
currentRow = currentSheet.createRow(++rowIndex);
currentRow.setHeightInPoints(18);
currentCell = currentRow.createCell(0);
currentCell.setCellStyle(cellStyles.get("blueStyle"));
currentCell.setCellValue("列名");
currentCell = currentRow.createCell(1);
currentCell.setCellStyle(cellStyles.get("blueStyle"));
currentCell.setCellValue("类型");
currentCell = currentRow.createCell(2);
currentCell.setCellStyle(cellStyles.get("blueStyle"));
currentCell.setCellValue("默认值");
currentCell = currentRow.createCell(3);
currentCell.setCellStyle(cellStyles.get("blueStyle"));
currentCell.setCellValue("释义");
// 表字段
String tableColumnsStr = tablePojo.getTableColumns();
for (String tableColumns : tableColumnsStr.split("@")) {
currentRow = currentSheet.createRow(++rowIndex);
currentRow.setHeightInPoints(18);
String[] tableColumnArr = tableColumns.split("#");
for (int i = 0; i < tableColumnArr.length; i++) {
currentCell = currentRow.createCell(i);
currentCell.setCellStyle(cellStyles.get("baseStyle"));
currentCell.setCellValue(tableColumnArr[i]);
}
}
}
}
currentWorkbook.write(fos);
}
} catch (Exception e) {
e.printStackTrace();
}
} /**
* 样式集锦
*
* @author ruran
* @since 2019年7月24日 下午7:32:26
* @param workbook
* @return
*/
private static Map<String, CellStyle> getCellStyles(Workbook workbook) {
// 实线边框
// style1.setBorderTop(BorderStyle.THIN);
// style1.setBorderBottom(BorderStyle.THIN);
// style1.setBorderLeft(BorderStyle.THIN);
// style1.setBorderRight(BorderStyle.THIN);
// 设置自动换行
// baseStyle.setWrapText(true); Map<String, CellStyle> cellStylesMap = new HashMap<>();
// baseStyle
CellStyle baseStyle = workbook.createCellStyle();
// 水平对齐方式
baseStyle.setAlignment(HorizontalAlignment.LEFT);
// 垂直对齐方式
baseStyle.setVerticalAlignment(VerticalAlignment.CENTER);
// 宋体设置
Font baseFont = workbook.createFont();
baseFont.setFontName("宋体");
baseStyle.setFont(baseFont);
cellStylesMap.put("baseStyle", baseStyle);// 存放样式-baseStyle // 深蓝色底部、白色字体、加粗
CellStyle bluesStyle = workbook.createCellStyle();
bluesStyle.cloneStyleFrom(cellStylesMap.get("baseStyle"));// 继承某样式
// 背景色
bluesStyle.setFillForegroundColor(IndexedColors.ROYAL_BLUE.getIndex());
bluesStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);// 这一行是必须的,不然会得不到想要的结果
// 白色加粗字体
Font bluesFont = workbook.createFont();
bluesFont.setColor(IndexedColors.WHITE.getIndex());
bluesFont.setBold(true);
bluesFont.setFontName("宋体");
bluesStyle.setFont(bluesFont);
cellStylesMap.put("bluesStyle", bluesStyle);// 存放样式-bluesStyle // 浅蓝色底部
CellStyle blueStyle = workbook.createCellStyle();
blueStyle.cloneStyleFrom(cellStylesMap.get("baseStyle"));// 继承某样式
// 背景色
blueStyle.setFillForegroundColor(IndexedColors.PALE_BLUE.getIndex());
blueStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);// 这一行是必须的,不然会得不到想要的结果
cellStylesMap.put("blueStyle", blueStyle);// 存放样式-blueStyle return cellStylesMap;
} /**
* 字符串判非空
*
* @author ruran
* @since 2019年7月23日 下午2:29:38
* @param str
* @return
*/
private static boolean isNotBlank(String str) {
if (null == str) {
return false;
}
if (str.trim().length() == 0) {
return false;
}
return true;
} /**
* 字符串判非空
*
* @author ruran
* @since 2019年7月23日 下午3:48:57
* @param str
* @return
*/
private static boolean isBlank(String str) {
if (null == str) {
return true;
}
if (str.trim().length() == 0) {
return true;
}
return false;
} /**
* 获取真实的表名 - 逻辑是去除末尾的数字
*
* @author ruran
* @since 2019年7月23日 下午3:51:03
* @param tableName
* @return
*/
private static String getRealTablename(String tableName) {
if (isBlank(tableName)) {
return null;
}
return tableName.replaceAll("\\d+$", ""); } /**
* 获取数据连接
*
* @author ruran
* @since 2019年7月29日 下午7:38:47
* @param ip
* @param user
* @param password
* @param database
* @return
*/
private static Connection getConnection(String ip, String user, String password, String database) {
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("成功加载MySQL驱动程序...");
Connection connention = DriverManager.getConnection("jdbc:mysql://" + ip + ":3306/" + database, user,
password);
System.out.println("成功建立MySQL连接...");
return connention;
} catch (Exception e) {
e.printStackTrace();
}
return null;
} /**
* 表数据内部类
*
* @author ruran
* @since 2019年7月23日 下午4:16:28
*/
@SuppressWarnings("unused")
private static class TablePojo {
String tableName = "";
String tableComment = "";
String tableColumns = ""; public TablePojo() { } public TablePojo(String tablename, String tablecomment, String tablecolumns) {
tableName = tablename;
tableComment = tablecomment;
tableColumns = tablecolumns;
} public String getTableName() {
return tableName;
} public void setTableName(String tableName) {
this.tableName = tableName;
} public String getTableComment() {
return tableComment;
} public void setTableComment(String tableComment) {
this.tableComment = tableComment;
} public String getTableColumns() {
return tableColumns;
} public void setTableColumns(String tableColumns) {
this.tableColumns = tableColumns;
} } }

[功能集锦] 003 - 一键生成mysql数据字典/数据库速查表的更多相关文章

  1. 使用 PowerDesigner 和 PDMReader 逆向生成 MySQL 数据字典

    下面提到的软件大家可以在下面的链接下载. 大家可以参考下面的操作录制视频来完成相关的操作. 使用 PowerDesigner 和 PDMReader 逆向生成 MySQL 数据字典.wmv_免费高速下 ...

  2. php 生成mysql数据字典代码

    由于项目开发用了比较多的表 ,为了快速获取数据字典,通过php代码的方式来获取表结构和表注释.代码如下: <?php /** * 生成mysql数据字典 */ header ( "Co ...

  3. php生成mysql数据字典

    <?php /** * 生成mysql数据字典 */ // 配置数据库 $database = array(); $database['DB_HOST'] = '127.0.0.1'; $dat ...

  4. php 生成mysql数据字典 (php5.5-5.6)

    <?php /** * 生成mysql数据字典 */ //配置数据库 $dbserver = "127.0.0.1"; $dbusername = "root&qu ...

  5. 生成mysql数据字典

    data_dictionary.php <?php /** * 生成mysql数据字典 */ header("Content-type: text/html; charset=utf- ...

  6. MySQL/MariaDB数据库的多表查询操作

    MySQL/MariaDB数据库的多表查询操作 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.单表查询小试牛刀 [root@node105.yinzhengjie.org.cn ...

  7. 支持MySql的数据库自动分表工具DBShardTools发布

    支持MySql的数据库自动分表工具DBShardTools发布 前段时间参与了公司的一个项目,这个项目的特点是数据量.访问量都比较大,考虑使用数据库水平分表策略,Google了大半天,竟然没有找到分表 ...

  8. Mysql MyISAM数据库批量转换表引擎为Innodb

    Mysql MyISAM数据库批量转换表引擎为Innodb 最近在做事物处理需要把表结构都改为带有支持事物的Innodb引擎格式, 把里面数据库 用户名.密码 等信息修改为你自己的,放在网站下运行即可 ...

  9. MySQL 判断数据库和数据表是否存在

    MySQL 判断数据库和数据表是否存在 如何使用SQL查询语句,判断数据库和数据表是否存在? 1.判断数据库是否存在 查询SQL如下: select * from information_schema ...

随机推荐

  1. C# 判断文件夹与文件是否存在

    //在上传文件时经常要判断文件夹是否存在,如果存在就上传文件,否则新建文件夹再上传文件 判断语句为 if (System.IO.Directory.Exists(Server.MapPath(&quo ...

  2. win32 socket编程(四)——服务器端实例(TCP)

    //Server服务器端Server.cpp 1 // 定义控制台应用程序的入口点. // #include "stdafx.h" #include <winsock2.h& ...

  3. js string相关方法

    1>concat()      //合并返回新的字符串 var a="么么么么",b="ssss"; a.concat(b) //"么么么么ss ...

  4. 行人重识别(ReID) ——基于深度学习的行人重识别研究综述

    转自:https://zhuanlan.zhihu.com/p/31921944 前言:行人重识别(Person Re-identification)也称行人再识别,本文简称为ReID,是利用计算机视 ...

  5. 2018-8-10-使用-Resharper-特性

    title author date CreateTime categories 使用 Resharper 特性 lindexi 2018-08-10 19:16:51 +0800 2018-4-25 ...

  6. MongoDb学习 自定义配置mongodb连接

    最近研究了mongodb获取本地连接属性的方案,场景就是mongodb的连接地址不在配置文件中配置,而是在代码中写好,代码中是从本地文件读取地址. public class MongoConfig { ...

  7. 使用Github 当作自己个人博客的图床

    使用Github 当作自己个人博客的图床 前提 本文前提: 我个人博客的草稿是存放在 github上的一个仓库 diarynote 截图存放的图片或者需要放在文章中图片,会固定存放在对应的文件夹中,我 ...

  8. 2020年的ARM处理器将超越英特尔

    2020年ARM真的会超越英特尔成为世界芯片霸主吗?迄今为止,基于ARM的笔记本电脑一直很流行,但在一两年内你可能会对它们产生不同的印象.该公司对其未来的处理器架构的性能预期提供了一个罕见的看法,这些 ...

  9. git点滴

    git指定版本,SHA-1短的,长的都可以 git checkout c66a9be git checkout c66a9befsadf1sdf1s3fd21 git log ##查询本地log gi ...

  10. SNOI2017 礼物

    题解 设前\(n\)个人的礼物个数和为\(F_n\), 那么显然\[F_n = 2 \times F_{n-1} + i^k\] 考虑矩阵快速幂 棘手的问题是:\(i^k\)不是可以直接用矩阵乘法可以 ...