[功能集锦] 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基础命令一(补充)
echo ls ls–l ---- ll cd / 根目录 cd ~ cd - 返回上一个目录 env ip addr 显示物理网络地址,缩写:ip a /etc/init.d/network ...
- Thymeleaf简介
Thymeleaf Thymeleaf简介 Thymeleaf是一个流行的模板引擎,该模板引擎采用Java语言开发,模板引擎是一个技术名词,是跨领域跨平台的概念,在Java语言体系下有模板引擎,在C# ...
- FCKeditor用在JSP中的几点注意事项
转自:https://blog.csdn.net/asinzy/article/details/3854127 本篇文章主要介绍了"FCKeditor用在JSP中的几点注意事项", ...
- MTCNN 人脸检测
demo.py import cv2 from detection.mtcnn import MTCNN # 检测图片中的人脸 def test_image(imgpath): mtcnn = MTC ...
- DateUtil-工具类
/** * 类描述:时间操作定义类 */public class DateUtils{ private static final Logger logger = Logger.getLogger(Da ...
- Test 6.24 T1 购物
问题描述 小 C 今天出去购物,商店里总共有 n 种商品,小 C 的钱够买至多 k 个商品. 小 C 对每种商品都有一个喜爱程度,但如果买了同一种商品很多次,小 C 对这种商品的喜爱程度就会降低. 具 ...
- 【leetcode】1041. Robot Bounded In Circle
题目如下: On an infinite plane, a robot initially stands at (0, 0) and faces north. The robot can recei ...
- elememt-ui 的 el-icon-iconName 图标 显示问题!
今天想在按钮处添加一个图标,但是显示不出.自己找了半天,终于找到了,希望帮到大家! 1,首先是没有报错的,但是有警告⚠ 意思是说什么拦截了之类的问题,但是到底是哪里问题导致拦截了呢?找了好久,原来是我 ...
- 调用搜狐IP地址库,根据不同访问者的IP,显示访问地址
<script src="http://pv.sohu.com/cityjson?ie=utf-8"></script> <script type ...
- 转载-使用Nodepad++来编辑我们服务器的配置文件
转自------------------ 作者:李阿昀 来源:CSDN 原文:https://blog.csdn.net/yerenyuan_pku/article/details/73128819 ...