当前位置:网站首页>Excel tool for generating database table structure
Excel tool for generating database table structure
2022-07-29 09:33:00 【[email protected】
Database table structure generation excel Tools
One 、 design sketch
Single table
The database table structure is as follows 
perform main After the method 
Generated excel file 
Multiple tables
Support the structure of all tables in the database , Generate excel

Two 、 How to use
pom file
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
Tool class
package com.mabo.database;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mabo.controller.TableInfo;
import com.mabo.excel.ExcelUtil;
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 java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
public class DatabaseUtils {
public static void main(String[] args) throws Exception {
String driver = "com.mysql.cj.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/xxx?serverTimezone=GMT";
String user = "root";
String password = "xxx";
// Generated excel File storage path
String filePath="G:/";
// All tables of the database are generated excel
// createDataBaseExcels(driver, url, user, password,filePath);
// Database file_info Table to generate excel
createDataBaseExcel(driver, url, user, password,"file_info",filePath);
}
public static void createDataBaseExcels(String driver, String url, String user, String password,String filePath) throws Exception {
JSONArray array = getTablesInfo(driver, url, user, password);
String[] strArray = {
" name ", " type ", " length ", " Required " ," notes "," remarks "};
createDataBaseExcels(array,strArray,filePath);
}
public static void createDataBaseExcel(String driver, String url, String user, String password,String tableName,String filePath) throws Exception {
String[] strArray = {
" name ", " type ", " length ", " Required " ," notes "," remarks "};
JSONArray jsonArray = getTableInfo(driver, url, user, password, tableName);
String fileName=filePath+tableName+".xls";
createDataBaseExcel(jsonArray, strArray,fileName);
System.out.println(tableName+" Table generation succeeded , File path : "+fileName);
}
/** * @Description : Generate all tables of the database excel * @Author : mabo */
public static void createDataBaseExcels(JSONArray jsonArray, String[] strArray,String filePath) throws IOException {
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String table = jsonObject.getString("table");
JSONArray fields = jsonObject.getJSONArray("fields");
String fileName=filePath+table+".xls";
createDataBaseExcel(fields, strArray,fileName);
System.out.println(table+" Table generation succeeded , File path : "+fileName);
}
}
/** * @Description : take fileName Table structure output to excel * @Author : mabo */
public static void createDataBaseExcel(JSONArray jsonArray, String[] strArray, String fileName) throws IOException {
// Create a webbook, Corresponding to one Excel file
HSSFWorkbook wb = new HSSFWorkbook();
// stay webbook Add a sheet, Corresponding Excel In the document sheet
HSSFSheet sheet = wb.createSheet("sheet1");
// stay sheet Add table header No 0 That's ok , Pay attention to the old version poi Yes Excel There is a limit to the number of rows and columns short
HSSFRow row = sheet.createRow(0);
// Add title line
HSSFCell cell = null;
for (int i = 0; i < strArray.length; i++) {
// Get the corresponding cells in the row
cell = row.createCell(i);
// Cell assignment
cell.setCellValue(strArray[i]);
}
// Write entity data , In practical application, these data are obtained from the database ,list The order of strings in must be the same as array strArray In the same order
int i = 0;
for (int j = 0; j < jsonArray.size(); j++) {
JSONObject json=jsonArray.getJSONObject(j);
i++;
row = sheet.createRow(i );
String name = json.getString("name");
String type = json.getString("type").toLowerCase();
Integer size = json.getInteger("size");
String isNeed=" yes ";
if (json.getBoolean("isNull").equals(true)){
isNeed=" no ";
}
String remarks = json.getString("remarks");
// Add data row
for (int z = 0; z < strArray.length; z++) {
cell = row.createCell(z);
// Get the corresponding cells in the row
// Cell assignment
if (z==0){
cell.setCellValue(name);
}
else if (z==1){
cell.setCellValue(type);
}
else if (z==2){
cell.setCellValue(size);
}
else if (z==3){
cell.setCellValue(isNeed);
}
else if (z==4){
cell.setCellValue(remarks);
}
}
}
// // Step six , Save the file to the specified location
FileOutputStream fout = new FileOutputStream(fileName);
try {
wb.write(fout);
fout.close();
} catch (Exception e) {
e.printStackTrace();
}
finally {
fout.close();
}
}
/** * Read database * All table structures */
public static JSONArray getTablesInfo(String driver, String url, String user, String password) throws Exception {
JSONArray array = new JSONArray();
Class.forName(driver);
Connection connection = DriverManager.getConnection(url, user, password);
DatabaseMetaData metaData = connection.getMetaData();
// Get all the table names from the metadata
String[] types = {
"TABLE"};
//mysql-connector-java 6.0 Use this method below
//rs = db.getTables(null, null, null, new String[] { "TABLE" });
//mysql-connector-java 6.x In this way
ResultSet tableResultSet = metaData.getTables(connection.getCatalog(), connection.getCatalog(), "%", types);
while (tableResultSet.next()) {
JSONObject json = new JSONObject();
String tableName = tableResultSet.getString("TABLE_NAME");
json.put("table",tableName);
// Get the table field structure
ResultSet columnResultSet = metaData.getColumns(null, "%", tableName, "%");
JSONArray fields = new JSONArray();
while (columnResultSet.next()) {
JSONObject field = new JSONObject();
// Field name
String columnName = columnResultSet.getString("COLUMN_NAME");
boolean repeat=false;
// Cycle to see if the current value repeats
for (int i = 0; i < fields.size(); i++) {
JSONObject jsonObject = fields.getJSONObject(i);
String column_name = jsonObject.getString("name");
if (columnName.equals(column_name)){
repeat=true;
break;
}
}
if (repeat){
continue;
}
field.put("name",columnName);
// data type
String columnType = columnResultSet.getString("TYPE_NAME");
field.put("type",columnType);
// Field length
int datasize = columnResultSet.getInt("COLUMN_SIZE");
field.put("size",datasize);
// Number of decimal places
int digits = columnResultSet.getInt("DECIMAL_DIGITS");
field.put("digits",digits);
// Can it be empty 1 Representative can be null 0 Representative cannot be empty
int nullable = columnResultSet.getInt("NULLABLE");
if (nullable==1){
field.put("isNull",true);
}
else {
field.put("isNull",false);
}
// describe
String remarks = columnResultSet.getString("REMARKS");
field.put("remarks",remarks);
fields.add(field);
}
json.put("fields",fields);
array.add(json);
}
return array;
}
/** * Read database * tableName Table structure */
public static JSONArray getTableInfo(String driver, String url, String user, String password,String tableName) throws Exception {
Class.forName(driver);
Connection connection = DriverManager.getConnection(url, user, password);
DatabaseMetaData metaData = connection.getMetaData();
// Get all the table names from the metadata
String[] types = {
"TABLE"};
//mysql-connector-java 6.0 Use this method below
//rs = db.getTables(null, null, null, new String[] { "TABLE" });
//mysql-connector-java 6.x In this way
ResultSet tableResultSet = metaData.getTables(connection.getCatalog(), connection.getCatalog(), "%", types);
while (tableResultSet.next()) {
JSONObject json = new JSONObject();
String table = tableResultSet.getString("TABLE_NAME");
if (table.equals(tableName)){
ResultSet columnResultSet = metaData.getColumns(null, "%", tableName, "%");
JSONArray fields = new JSONArray();
while (columnResultSet.next()) {
JSONObject field = new JSONObject();
// Field name
String columnName = columnResultSet.getString("COLUMN_NAME");
boolean repeat=false;
// Cycle to see if the current value repeats
for (int i = 0; i < fields.size(); i++) {
JSONObject jsonObject = fields.getJSONObject(i);
String column_name = jsonObject.getString("name");
if (columnName.equals(column_name)){
repeat=true;
break;
}
}
if (repeat){
continue;
}
field.put("name",columnName);
// data type
String columnType = columnResultSet.getString("TYPE_NAME");
field.put("type",columnType);
// Field length
int datasize = columnResultSet.getInt("COLUMN_SIZE");
field.put("size",datasize);
// Number of decimal places
int digits = columnResultSet.getInt("DECIMAL_DIGITS");
field.put("digits",digits);
// Can it be empty 1 Representative can be null 0 Representative cannot be empty
int nullable = columnResultSet.getInt("NULLABLE");
if (nullable==1){
field.put("isNull",true);
}
else {
field.put("isNull",false);
}
// describe
String remarks = columnResultSet.getString("REMARKS");
field.put("remarks",remarks);
fields.add(field);
}
return fields;
}
}
return null;
}
}
版权声明
本文为[[email protected]]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/210/202207290925453134.html
边栏推荐
猜你喜欢

Unity xchart3.0 basic usage quick start

深入浅出依赖注入及其在抖音直播中的应用

网络安全(6)

23考研人撑住!考研第一波弃考高峰期已经到来!
![[Apple Developer account]06 after transferring the developer account, the annual fee of the developer is automatically renewed](/img/a7/12fd63f16ebca81a3dd2d1b97847d1.png)
[Apple Developer account]06 after transferring the developer account, the annual fee of the developer is automatically renewed

36. JS animation
![[Bert multi label text classification practice] I - overview of practical projects](/img/47/3e6cf5d49e41a03ea7f9b6eb295e1d.png)
[Bert multi label text classification practice] I - overview of practical projects

Gao Zhiwei: data management enables the digital transformation of the transportation industry

Emmet syntax

Unity Xchart3.0基本用法快速上手
随机推荐
How to introduce your project experience?
Using logistic regression and neural network to deal with complex binary classification problems
RTMP supports h265 streaming
Basic part 2 of flowable
Visual Studio
36. JS animation
OpenCV入门基础学习
基于C语言模拟实现DFA识别字符串
36. JS动画
Solve the problem of reading data garbled by redis visualization tool
【机器学习】朴素贝叶斯代码练习
QoS服务质量五QoS边界行为之流量整形
[performance optimization methodology series] III. core idea of performance optimization (2)
数仓项目踩坑记录与解决方法总结
Emmet syntax
MySQL事务与MVCC如何实现的隔离级别
Acwing game 59 [End]
网络安全(5)
smart-webcomponents 14.2.0 Crack
[unity entry program] C # and unity - understand classes and objects