When I usually create database tables , It is customary to list the fields to be used in Notepad first , Write field names and comments , Like this


Then read the text with code , Pass Chinese colon : separate , Get name and comment , Re pass create Create table statement , Add field name , Notes stitched together , generate sql output . The field type is not considered in this generation , length , It needs to be set after the table is created .

Then I have nothing to do today , Think about standardizing , When listing the fields to be used , Just design the type and length , Execution completed sql Then you don't have to change one by one . So I use excel form ( It looks good ), like this

Unlimited number of lines , There are only four columns , The first line must be Table notes : Table name , Separated by English colons ( See what symbols you like to use , Just change it in the code ), There can be more than one sheet.

<> Let's see the generated effect first :

<> code :
import cn.hutool.core.util.StrUtil; import cn.hutool.poi.excel.WorkbookUtil;
import lombok.Data; import org.apache.poi.ss.usermodel.*; import org.junit.Test;
import java.io.*; import java.util.ArrayList; import java.util.HashMap; import
java.util.List; import java.util.Map; public class GenerateSqlUtil { @Data
public static class ExcelEntity{ /** Field name */ private String filedName; /** Field type
*/ private String filedType; /** field comment */ private String notes; /** Field properties */
private String attribute; } /** * generate sql file */ @Test public void generateSql()
throws IOException { System.out.println(" Start build SQL=========================");
//Map<String, Object> map = readExcel(null,null," User table "); // Read single assignment sheet data List<Map
<String, Object>> result = readExcel(); System.out.println("============== common "+
result.size()+" Zhang Biao ==============="); StringBuilder sb = new StringBuilder(); for
(Map<String, Object> map : result) { List<ExcelEntity> list = (List<ExcelEntity>
) map.get("list"); int size = list.size(); // Table name String tableName = (String) map.
get("tableName"); // notes String tableNotes = (String) map.get("tableNotes"); sb.
append(String.format("-- %s:%s\n", tableName,tableNotes)); sb.append(String.
format("DROP TABLE IF EXISTS %s;\n", tableName)); sb.append(String.format(
"CREATE TABLE %s (\n", tableName)); for (int i = 0; i < size; i++) {
ExcelEntity entity= list.get(i); sb.append(String.format("\t%s %s", entity.
getFiledName(),entity.getFiledType())); String type = entity.getFiledType();
String attribute= entity.getAttribute(); // Set primary key if (attribute.contains(" Primary key ")){
sb.append(" PRIMARY KEY"); }else { // character string , Text setting encoding // When the primary key type is character , No coding if (type.
contains("char") || type.contains("text")){ sb.append(" CHARACTER SET utf8mb4
COLLATE utf8mb4_unicode_ci"); } } if (attribute.contains(" Required ")){ sb.append("
NOT NULL COMMENT "); }else { sb.append(" NULL DEFAULT NULL COMMENT "); } sb.
append(String.format("'%s'",entity.getNotes())); if (i < size-1){ sb.append(",")
; } sb.append("\n"); } sb.append(String.format(") ENGINE = InnoDB CHARACTER SET
= utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = '%s' ROW_FORMAT = Dynamic;",
tableNotes)); sb.append("\n\n"); } //sql Output location File file=new File(
"C:\\Users\\Admin\\Desktop\\sql.sql"); FileOutputStream fos1=new
FileOutputStream(file); OutputStreamWriter dos1=new OutputStreamWriter(fos1);
dos1.write(sb.toString()); dos1.close(); System.out.println(
"SQL Build complete ========================="); } /** * Read assignment sheet Data of , Get table name , Field name , Field type , field comment , attribute
*/ public Map<String,Object> readExcel(File file,Workbook book,String sheetName)
{ Map<String,Object> map = new HashMap<>(); List<ExcelEntity> list = new
ArrayList<>(); if (file == null){ file = new File(
"C:\\Users\\Admin\\Desktop\\1.xlsx"); } if (book == null){ //WorkbookUtil
hutool Tools for book = WorkbookUtil.createBook(file); } Sheet sheet = book.getSheet(
sheetName); // The first line is the header , Default is notes : Table name Row titleRow = sheet.getRow(0); String title =
titleRow.getCell(0).toString(); map.put("tableName",title.split(":")[1]); map.
put("tableNotes",title.split(":")[0]); // The second line is the title , Do not read . The third line starts with data int lastRowNum =
sheet.getLastRowNum(); for(int i = 2; i <= lastRowNum; i++){ list.add(getEntity(
sheet.getRow(i))); } map.put("list",list); return map; } /** * Read multiple sheet Data of */
public List<Map<String,Object>> readExcel() { List<Map<String,Object>> result =
new ArrayList<>(); File file = new File("C:\\Users\\Admin\\Desktop\\1.xlsx");
Workbook book= WorkbookUtil.createBook(file); int sheetNum = book.
getNumberOfSheets(); for (int i = 0; i < sheetNum; i++) { String sheetName =
book.getSheetName(i); result.add(readExcel(file,book,sheetName)); } return
result; } private ExcelEntity getEntity(Row row){ ExcelEntity entity = new
ExcelEntity(); // Number of columns :4 column , Field names , Field type , field comment , Field properties for (int j = 0; j < 4; j++) {
String str= row.getCell(j).toString(); if (StrUtil.isNotBlank(str)){ switch (j){
case 0: entity.setFiledName(str); break; case 1: entity.setFiledType(str); break
; case 2: entity.setNotes(str); break; case 3: entity.setAttribute(str); break;
} } } return entity; } }

Technology
©2019-2020 Toolsou All rights reserved,
Solve in servlet The Chinese output in is a question mark C String function and character function in language MySQL management 35 A small coup optimization Java performance —— Concise article Seven sorting algorithms (java code ) use Ansible Batch deployment SSH Password free login to remote host according to excel generate create Build table SQL sentence Spring Source code series ( sixteen )Spring merge BeanDefinition Principle of Virtual machine installation Linux course What are the common exception classes ?