[功能集锦] 003 - 一键生成mysql数据字典/数据库速查表
写在前面:
因为工作时候经常遇到半路接手项目的情况,由于年代久远,数据库字典这块经常缺失。故写此篇,以便复用,也希望对大家有点帮助。
随笔内容不高级,如有不妥,不吝指正。
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数据字典/数据库速查表的更多相关文章
- 使用 PowerDesigner 和 PDMReader 逆向生成 MySQL 数据字典
下面提到的软件大家可以在下面的链接下载. 大家可以参考下面的操作录制视频来完成相关的操作. 使用 PowerDesigner 和 PDMReader 逆向生成 MySQL 数据字典.wmv_免费高速下 ...
- php 生成mysql数据字典代码
由于项目开发用了比较多的表 ,为了快速获取数据字典,通过php代码的方式来获取表结构和表注释.代码如下: <?php /** * 生成mysql数据字典 */ header ( "Co ...
- php生成mysql数据字典
<?php /** * 生成mysql数据字典 */ // 配置数据库 $database = array(); $database['DB_HOST'] = '127.0.0.1'; $dat ...
- php 生成mysql数据字典 (php5.5-5.6)
<?php /** * 生成mysql数据字典 */ //配置数据库 $dbserver = "127.0.0.1"; $dbusername = "root&qu ...
- 生成mysql数据字典
data_dictionary.php <?php /** * 生成mysql数据字典 */ header("Content-type: text/html; charset=utf- ...
- MySQL/MariaDB数据库的多表查询操作
MySQL/MariaDB数据库的多表查询操作 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.单表查询小试牛刀 [root@node105.yinzhengjie.org.cn ...
- 支持MySql的数据库自动分表工具DBShardTools发布
支持MySql的数据库自动分表工具DBShardTools发布 前段时间参与了公司的一个项目,这个项目的特点是数据量.访问量都比较大,考虑使用数据库水平分表策略,Google了大半天,竟然没有找到分表 ...
- Mysql MyISAM数据库批量转换表引擎为Innodb
Mysql MyISAM数据库批量转换表引擎为Innodb 最近在做事物处理需要把表结构都改为带有支持事物的Innodb引擎格式, 把里面数据库 用户名.密码 等信息修改为你自己的,放在网站下运行即可 ...
- MySQL 判断数据库和数据表是否存在
MySQL 判断数据库和数据表是否存在 如何使用SQL查询语句,判断数据库和数据表是否存在? 1.判断数据库是否存在 查询SQL如下: select * from information_schema ...
随机推荐
- Linux基础之输入输出
第十五章 输入输出 一.重定向概述 1.1.什么是重定向? 将原本要输出到屏幕的数据信息,重新定向到指定的文件中. 比如:每天凌晨定时备份数据,希望将备份数据的结果保存到某个文件中.这样第二天通过查看 ...
- [Luogu2014]选课(树形dp)
[Luogu2014]选课 题目描述 在大学里每个学生,为了达到一定的学分,必须从很多课程里选择一些课程来学习,在课程里有些课程必须在某些课程之前学习,如高等数学总是在其它课程之前学习.现在有N门功课 ...
- 【技巧】Windows 10 1809无法接收1903解决方法
这都7月份了,Windows10 1903都升级的有一个月了,然而我的1809的系统一直找不到1903的更新. 虽说1903会有bug,但还是想体验一把.周围同事都更新了,心里还是痒痒的. 于是每天都 ...
- 实现memcpy()函数及过程总结
1.为什么会写memcpy 在之前的应聘笔试上遇到一道笔试题,题目要求实现一个my_memcpy函数.函数原型:void * my_memcpy(void *dst, const void *src, ...
- ArrayUtils工具类更加方便的操作数据
不废话,上代码: package com.jxd; import org.apache.commons.lang3.ArrayUtils; public class TestArr { /** * A ...
- 线程工具类 - CyclicBarrier(循环栅栏)
CyclicBarrier官方文档 一.原理 CyclicBarrier是另外一种多线程并发控制实用工具.它和CountDownLatch非常类似,它也可以实现线程的计数等待,但它的功能比CountD ...
- LocalDateTime用法(jdk1.8 )
前言 最近看别人项目源码,发现Java8新的日期时间API很方便强大,所以转载该入门介绍博客,记录一下. 使用新时间日期API的必要性 在java8以前,或许: 当你在做有关时间日期的操作时,你会想到 ...
- Java缓冲流高效大文件的复制实例
public class BufferedDemo { public static void main(String[] args) throws FileNotFoundException { // ...
- 命令——tr
文本处理工具命令——tr 一帮助说明 TR() User Commands TR() NAME tr - translate or delete characters SYNOPSIS tr [OPT ...
- C++ 单链表模板类实现
单链表的C语言描述 基本运算的算法——置空表.求表的长度.取结点.定位运算.插入运算.删除运算.建立不带头结点的单链表(头插入法建表).建立带头结点的单链表(尾插入法建表),输出带头结点的单链表 #i ...