大家好,我是成都分院12期学员晋良金,今天为大家介绍如何生成sql文件。
1.背景介绍
基本上每一个项目都会抽象出也业务相对应的表,需要我们在数据库中创建对应的表,才能继续后续对表的CRUD的相关开发工作。如果只有几张表,我们可以手动在数据库中创建,那么如果有几十上百张表呢,这个时候就需要使用sql文件进行批量创建。如何生成sql文件就成了最根本的问题了。
2.知识剖析
什么是.sql文件
(1)*.sql 从本质上说就是个文本文件;
(2)是数据库执行语句的脚本文件。
如何生成创建数据库表的sql文件
(1)通过JPA“曲线救国”。因为JPA可以选择在代码运行的时候对实体类相对应的数据库中的表的执行策略ddl-auto:update、create、none、create-drop、validate。可以配置成update、create,这样在第一次运行的时候,会在数据库中新建表,然后通过命令行或者Navicat导出数据库即可。
(2)使用java代码生成
——将表按一定规则输入到Excel文件之中;
——通过代码读取Excel文件中的内容;
代码
public static List<DataTable> readXlsx(String path) { List<DataTable> list = new ArrayList<>(); try { InputStream in = new FileInputStream(path);// 读取excel文件 XSSFWorkbook xssfWorkbook = new XSSFWorkbook(in);// XSSFWorkbook实例对应一个excel文件 for (int i = 0; i < xssfWorkbook.getNumberOfSheets(); i++) {// 遍历行XSSFSheet XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(i); if (xssfSheet == null) { continue; } for (int r = 0; r <= xssfSheet.getLastRowNum(); r++) {// 逐行读取内容 XSSFRow xssfRow = xssfSheet.getRow(r); if (xssfRow != null) { // 如果哨兵等于0,代表这一行是不需要读取的。continue之后自减1 if (sentry-- == 0) { continue; } CellType cellType2 = xssfRow.getCell(2).getCellTypeEnum(); CellType cellType3 = xssfRow.getCell(3).getCellTypeEnum(); if (cellType2 == CellType.BLANK && cellType3 == CellType.BLANK) { ++tableNum; sentry = 0; String name = xssfRow.getCell(0).getStringCellValue().toLowerCase(); String comment = xssfRow.getCell(1).getStringCellValue(); list.add(new DataTable(name, comment)); System.out.println("========================table======================"); System.out.println("表名:" + name + ",注释:" + comment); continue; } if (cellType3 == CellType.NUMERIC) { list.get(list.size() - 1).getFields().add(new TableField( xssfRow.getCell(0).getStringCellValue(), xssfRow.getCell(1).getStringCellValue(), xssfRow.getCell(2).getStringCellValue(), xssfRow.getCell(3).getStringCellValue() )); } else { list.get(list.size() - 1).getFields().add(new TableField( xssfRow.getCell(0).getStringCellValue(), xssfRow.getCell(1).getStringCellValue(), xssfRow.getCell(2).getStringCellValue(), xssfRow.getCell(3).getStringCellValue() )); } } } } in.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return list; }
——将读取到的内容进行拼接,并输出到sql文件之中
3.常见问题
4.解决方案
5.编码实战
6.扩展思考
7.参考文献
https://blog.csdn.net/u010746364/article/details/53078537
https://www.cnblogs.com/LUA123/p/8666245.html
8.更多讨论
(1)推荐使用哪种方式
如果数量少的话,用哪种都无所谓;如果有几十张表的话推荐通过Excel生成sql文件创建表,再通过mybatis逆向工程生成实体类。
(2)poi依赖还可用于什么地方
既然可以使用它读取Excel文件,那么同样可以利用它向Excel文件中写入数据。
(3)Excel内容格式可以改变吗?
可以的,只需要在读取的时候改变读取规则即可。