声明:本文参考自:https://www.cnblogs.com/linyb-geek/p/14436059.html
如何实现这个sql脚本
实现这个sql脚本的方式有很多种,本文就讲下利用java程序生成这个sql脚本。生成这个sql脚本的关键在于DatabaseMetaData这个类,这个类是啥?它是java.sql包中的类,利用它可以获取我们连接到的数据库的结构、存储等很多信息
其更多详细介绍可以查看如下链接:https://www.apiref.com/java11-zh/java.sql/java/sql/DatabaseMetaData.html
核心代码实现
1、获取数据库下的所有数据库表名
/** * 获取数据库下的所有数据库表名 * * @return Map<String, List<String>> key为数据库名称,value为该数据库下的所有表名 */ public Map<String, List<String>> getDbTablesNamesMap(){ Map<String, List<String>> dbTableNamesMap = new HashMap<>(); try { //获取数据库的元数据 DatabaseMetaData dbMetaData = getConnection().getMetaData(); //从元数据中获取到所有的表名 ResultSet rs = dbMetaData.getTables(null, null, null,new String[] { "TABLE" }); List<String> tableNames; while(rs.next()) { String tableName = rs.getString("TABLE_NAME"); String curTableDbName = rs.getString("TABLE_CAT"); String tableNameType = rs.getString("TABLE_TYPE"); //表模式(可能为空),在oracle中获取的是命名空间 String tableNameSchema = rs.getString("TABLE_SCHEM"); String tableNameRemark = rs.getString("REMARKS"); System.out.println("表名: " + tableName + ",表所属数据库: " + curTableDbName + ",表类型: " + tableNameType + ",表模式: " + tableNameSchema + ",表备注: " + tableNameRemark); //跳过mysql自带的系统库 if("sys".equalsIgnoreCase(curTableDbName)){ continue; } if(dbTableNamesMap.containsKey(curTableDbName)){ tableNames = dbTableNamesMap.get(curTableDbName); }else{ tableNames = new ArrayList<>(); } tableNames.add(tableName); dbTableNamesMap.put(curTableDbName,tableNames); } } catch (SQLException throwables) { throwables.printStackTrace(); } close(); return dbTableNamesMap; }
2、拼凑要执行的sql语句
public static List<String> prepareSqlStatementWithStringFormat(boolean isForFiles) { String sql = "alter table %s ADD COLUMN create_time DATETIME COMMENT ‘创建时间‘,ADD COLUMN created_by_id BIGINT(20) DEFAULT NULL COMMENT ‘创建人id‘, ADD COLUMN update_time DATETIME COMMENT ‘修改时间‘, ADD COLUMN last_updated_by_id BIGINT(20) DEFAULT NULL COMMENT ‘修改人id‘"; List<String> sqlStatements = new ArrayList<>(); Map<String, List<String>> dbTableNamesMap = DbUtils.INSTANCE.getDbTablesNamesMap(); dbTableNamesMap.forEach((dbName,tableNames) -> { for (String tableName : tableNames) { String record = dbName + "." + tableName; String sqlStatement = String.format(sql, record); //如果是要写入文件,则每条生成的sql语句,需追加分号 if(isForFiles){ sqlStatement = sqlStatement + ";"; } System.out.println(sqlStatement); sqlStatements.add(sqlStatement); } }); return sqlStatements; }
3、将生成的sql语句写入文件
public static void writeSqlStatement2File(List<String> sqlStatements,String filePath){ try { File file = new File(filePath); if(!file.exists()){ file.createNewFile(); } FileUtil.writeUtf8Lines(sqlStatements,file); System.out.println("数据库脚本写入"+filePath+"成功"); } catch (IOException e) { e.printStackTrace(); System.out.println("数据库脚本写入"+filePath+"失败"); } }
demo链接
https://github.com/lyb-geek/springboot-learning/tree/master/springboot-generate-sqlscript