对比DB库中所有表差异,导出csv文件
平时工作中会要求对比不同环境下的DB库中所有表的差异,包含字段差异、字段类型、字段注释、字段默认值等,网上查了很多资料发现并不能很好的满足我的要求,最终搞了一下把这些差异生成CSV文件
最终成品如下
废话不多说,直接上代码
package com.xx.xx.xx.utility;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.hutool.poi.excel.StyleSet;
import com.alibaba.druid.pool.DruidDataSource;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.io.FileUtils;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.jdbc.core.JdbcTemplate;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.stream.Collectors;
public class DBDiffUtil {
static final String Å="xxx";
static final String SGDBName="xxxx";
static final String SIT1 = "jdbc:mysql://xxxx:xx/"+IDDBName+"?useSSL=false";
static final String SIT3 = "jdbc:mysql://xxx:xx/"+SGDBName+"?useSSL=false";
static final String tableSql =
"SELECT TABLE_SCHEMA,TABLE_NAME, " +
" TABLE_COMMENT FROM " +
" information_schema.`TABLES` " +
"WHERE " +
" TABLE_SCHEMA = '%s'";
static final String schemaSQL = "SELECT " +
"COLUMN_NAME,DATA_TYPE,IS_NULLABLE,COLUMN_DEFAULT ,COLUMN_COMMENT " +
"FROM INFORMATION_SCHEMA.COLUMNS " +
"where table_schema = '%s' AND table_name = '%s'";
private static JdbcTemplate db1;
private static JdbcTemplate db2;
static {
db1 = new JdbcTemplate();
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl(SIT1);
dataSource.setUsername("xxx");
dataSource.setPassword("xxx");
db1.setDataSource(dataSource);
db2 = new JdbcTemplate();
DruidDataSource dataSource2 = new DruidDataSource();
dataSource2.setUrl(SIT3);
dataSource2.setUsername("xxx");
dataSource2.setPassword("xxx");
db2.setDataSource(dataSource2);
}
public static void main(String[] args) throws IOException {
Set<String> idTables = db1.queryForList(String.format(tableSql, IDDBName)).stream().map(e -> e.get("TABLE_NAME").toString()).collect(Collectors.toSet());
Set<String> sgTables = db2.queryForList(String.format(tableSql, SGDBName)).stream().map(e -> e.get("TABLE_NAME").toString()