使用screw来对比数据库表和字段差异
mhr18 2025-01-14 15:51 15 浏览 0 评论
1.Screw 库简介
Screw 是一个用于 数据库结构分析和文档生成的 Java 库。它支持多种数据库,包括 MySQL、PostgreSQL 和 Oracle。Screw 可以帮助开发者快速获取数据库的表结构、字段信息,并进行比较。
2.原理
使用 Screw 库对比数据库表和字段的基本原理如下:
- 连接数据库:使用 JDBC 连接到需要对比的两个数据库。
- 获取表结构:使用 Screw 提供的 API 获取每个数据库中的表和字段信息。
- 比较表和字段:将两个数据库的表和字段信息进行比较,识别出存在的差异。
- 生成报告:将比较结果生成报告,方便后续查看和分析。
3.环境搭建
第一个mysql数据库
docker run --name docker-mysql -e MYSQL_ROOT_PASSWORD=123456 -p 3306:3306 -d mysql
初始化数据
CREATE DATABASE database1;
USE database1;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL UNIQUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE orders (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
product_name VARCHAR(100) NOT NULL,
quantity INT NOT NULL,
order_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id)
);
CREATE DATABASE database2;
USE database2;
CREATE TABLE customers (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL UNIQUE,
registered_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE purchases (
id INT AUTO_INCREMENT PRIMARY KEY,
customer_id INT NOT NULL,
item_name VARCHAR(100) NOT NULL,
amount INT NOT NULL,
purchase_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (customer_id) REFERENCES customers(id)
);
CREATE TABLE orders (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
quantity INT NOT NULL,
order_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
说明
msyql账号root
mysql密码123456
4.代码工程
目标
使用 Screw 库对比两个 MySQL 数据库表和字段
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>springboot-demo</artifactId>
<groupId>com.et</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>Screw</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>cn.smallbun.screw</groupId>
<artifactId>screw-core</artifactId>
<version>1.0.5</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.3</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.24.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.24.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
</dependencies>
</project>
对比代码
package com.et;
import cn.smallbun.screw.core.query.DatabaseQuery;
import cn.smallbun.screw.core.query.mysql.MySqlDataBaseQuery;
import cn.smallbun.screw.core.query.mysql.model.MySqlColumnModel;
import cn.smallbun.screw.core.query.mysql.model.MySqlTableModel;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.poi.xwpf.usermodel.*;
import javax.sql.DataSource;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DatabaseComparison {
public static void main(String[] args) {
// Configure database connection information
HikariConfig hikariConfig1 = new HikariConfig();
hikariConfig1.setDriverClassName("com.mysql.cj.jdbc.Driver");
hikariConfig1.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/database1");
hikariConfig1.setUsername("root");
hikariConfig1.setPassword("123456");
hikariConfig1.addDataSourceProperty("useInformationSchema", "true");
hikariConfig1.setMinimumIdle(2);
hikariConfig1.setMaximumPoolSize(5);
DataSource dataSource1 = new HikariDataSource(hikariConfig1);
DatabaseQuery query1 = new MySqlDataBaseQuery(dataSource1);
HikariConfig hikariConfig2 = new HikariConfig();
hikariConfig2.setDriverClassName("com.mysql.cj.jdbc.Driver");
hikariConfig2.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/database2");
hikariConfig2.setUsername("root");
hikariConfig2.setPassword("123456");
hikariConfig2.addDataSourceProperty("useInformationSchema", "true");
hikariConfig2.setMinimumIdle(2);
hikariConfig2.setMaximumPoolSize(5);
DataSource dataSource2 = new HikariDataSource(hikariConfig2);
DatabaseQuery query2 = new MySqlDataBaseQuery(dataSource2);
try {
// Retrieve table structure
List<MySqlTableModel> tableInfos1 = (List<MySqlTableModel>) query1.getTables();
List<MySqlTableModel> tableInfos2 = (List<MySqlTableModel>) query2.getTables();
// Create Word document
XWPFDocument document = new XWPFDocument();
XWPFParagraph titleParagraph = document.createParagraph();
titleParagraph.createRun().setText("Database Table and Field Comparison");
titleParagraph.setAlignment(ParagraphAlignment.CENTER);
// Create table for database comparison
XWPFTable table = document.createTable();
XWPFTableRow headerRow = table.getRow(0);
headerRow.getCell(0).setText("Table Name");
headerRow.addNewTableCell().setText("Exists in Database 1");
headerRow.addNewTableCell().setText("Exists in Database 2");
// Compare tables
Map<String, MySqlTableModel> tableMap1 = new HashMap<>();
for (MySqlTableModel tableInfo : tableInfos1) {
tableMap1.put(tableInfo.getTableName(), tableInfo);
}
Map<String, MySqlTableModel> tableMap2 = new HashMap<>();
for (MySqlTableModel tableInfo : tableInfos2) {
tableMap2.put(tableInfo.getTableName(), tableInfo);
}
// Record table differences
for (String tableName : tableMap1.keySet()) {
XWPFTableRow row = table.createRow();
row.getCell(0).setText(tableName);
row.getCell(1).setText("Yes");
row.getCell(2).setText(tableMap2.containsKey(tableName) ? "Yes" : "No");
}
for (String tableName : tableMap2.keySet()) {
if (!tableMap1.containsKey(tableName)) {
XWPFTableRow row = table.createRow();
row.getCell(0).setText(tableName);
row.getCell(1).setText("No");
row.getCell(2).setText("Yes");
}
}
// Add table differences title
document.createParagraph().createRun().setText("\nTable Differences:");
for (String tableName : tableMap1.keySet()) {
if (!tableMap2.containsKey(tableName)) {
document.createParagraph().createRun().setText("Table " + tableName + " does not exist in Database 2");
} else {
compareColumns(document, tableMap1.get(tableName), tableMap2.get(tableName), query1, query2);
}
}
for (String tableName : tableMap2.keySet()) {
if (!tableMap1.containsKey(tableName)) {
document.createParagraph().createRun().setText("Table " + tableName + " does not exist in Database 1");
}
}
// Save Word document
try (FileOutputStream out = new FileOutputStream("D://tmp/Database_Comparison.docx")) {
document.write(out);
}
System.out.println("Database table and field differences have been generated in the Word document.");
} catch (Exception e) {
e.printStackTrace();
System.out.println("An error occurred: " + e.getMessage());
}
}
private static void compareColumns(XWPFDocument document, MySqlTableModel mySqlTableModel1, MySqlTableModel mySqlTableModel2, DatabaseQuery query1, DatabaseQuery query2) {
// Retrieve column information for both tables
List<MySqlColumnModel> columnNames1 = (List<MySqlColumnModel>) query1.getTableColumns(mySqlTableModel1.getTableName());
List<MySqlColumnModel> columnNames2 = (List<MySqlColumnModel>) query2.getTableColumns(mySqlTableModel2.getTableName());
// Create mappings from column names to column models
Map<String, MySqlColumnModel> columnsMap1 = new HashMap<>();
for (MySqlColumnModel column : columnNames1) {
columnsMap1.put(column.getColumnName(), column);
}
Map<String, MySqlColumnModel> columnsMap2 = new HashMap<>();
for (MySqlColumnModel column : columnNames2) {
columnsMap2.put(column.getColumnName(), column);
}
// Create column difference table
XWPFTable columnTable = document.createTable();
XWPFTableRow columnHeaderRow = columnTable.getRow(0);
columnHeaderRow.getCell(0).setText("Column Name");
columnHeaderRow.addNewTableCell().setText("Exists in Database 1");
columnHeaderRow.addNewTableCell().setText("Exists in Database 2");
// Compare columns
for (String columnName : columnsMap1.keySet()) {
XWPFTableRow row = columnTable.createRow();
row.getCell(0).setText(columnName);
row.getCell(1).setText("Yes");
row.getCell(2).setText(columnsMap2.containsKey(columnName) ? "Yes" : "No");
if (!columnsMap2.containsKey(columnName)) {
document.createParagraph().createRun().setText("Column " + columnName + " does not exist in table " + mySqlTableModel2.getTableName());
} else {
// Compare column types and other properties
MySqlColumnModel column1 = columnsMap1.get(columnName);
MySqlColumnModel column2 = columnsMap2.get(columnName);
// Compare column types
if (!column1.getDataType().equals(column2.getDataType())) {
document.createParagraph().createRun().setText("Column " + columnName + " in table " + mySqlTableModel1.getTableName() + " has type " + column1.getDataType() +
", while in table " + mySqlTableModel2.getTableName() + " it has type " + column2.getDataType());
}
}
}
// Check reverse differences
for (String columnName : columnsMap2.keySet()) {
if (!columnsMap1.containsKey(columnName)) {
document.createParagraph().createRun().setText("Column " + columnName + " does not exist in table " + mySqlTableModel1.getTableName());
}
}
}
}
代码解析
- 数据库连接配置:使用 HikariCP 配置数据库连接信息,包括数据库 URL、用户名和密码。
- 获取表结构:通过 query.getTables() 方法获取数据库中的表信息。
- 比较表:将两个数据库的表信息存储在 Map 中,并进行比较,输出存在于一个数据库但不存在于另一个数据库的表。
- 比较字段:在比较表的同时,调用 compareColumns 方法获取字段信息,并进行比较,输出字段的存在性和类型差异。
以上只是一些关键代码,所有代码请参见下面代码仓库
代码仓库
- https://github.com/Harries/springboot-demo(screw)
5.测试
运行测试类的main方法,将结果写入word文档
6.引用
- https://www.liuhaihua.cn/archives/711972.html
相关推荐
- 甲骨文签署多项大型云协议,其一未来可贡献超300亿美元年收入
-
IT之家7月1日消息,根据甲骨文Oracle当地时间6月30日向美国证券交易委员会(SEC)递交的FORM8-K文件,该企业在始于2025年6月1日的202...
- 甲骨文获TEMU巨额合同,后者大部分基础设施将迁移至Oracle云
-
IT之家6月23日消息,Oracle甲骨文创始人、董事长兼首席技术官LarryEllison(拉里埃里森)在本月早些时候的2025财年第四财季和全财年财报电话会议上表示,Oracle...
- Spring Boot 自定义数据源设置,这些坑你踩过吗?
-
你在使用SpringBoot进行后端开发的过程中,是不是也遇到过这样的问题:项目上线后,数据库连接总是不稳定,偶尔还会出现数据读取缓慢的情况,严重影响了用户体验。经过排查,发现很大一部分原因竟然...
- 一个开箱即用的代码生成器(一个开箱即用的代码生成器是什么)
-
今天给大家推荐一个好用的代码生成器,名为renren-generator,该项目附带前端页面,可以很方便的选择我们所需要生成代码的表。首先我们通过git工具克隆下来代码(地址见文末),导入idea。...
- 低代码建模平台-数据挖掘平台(低代码平台的实现方式)
-
现在来看一下数据连接。·这里是管理数据连接的空间,点击这里可以新增一个数据连接。·输入连接名称,然后输入url,是通过gdbc的方式去连接的数据库,目前是支持mysql、oracle以及国产数据库达梦...
- navicat 17.2.7连接oracle数据库提示加载oracle库失败
-
系统:macOS15.5navicat版本:navicatpremiumlite17.2.7连接oracle测试报错:加载oracle库失败【解决办法】:放达里面找到程序,显示简介里面勾选“使...
- 开源“Windows”ReactOS更新:支持全屏应用
-
IT之家6月17日消息,ReactOS团队昨日(6月16日)在X平台发布系列推文,公布了该系统的最新进展,包括升级Explorer组件,支持全屏应用,从Wine项目引入了...
- SSL 推出采用全模拟内置混音技术的模拟调音台Oracle
-
英国调音台传奇品牌SolidStateLogic宣布推出Oracle——一款采用全模拟内置混音技术的调音台,在紧凑的AWS尺寸机箱内集成了大型调音台的功能。该调音台提供24输入和...
- 47道网络工程师常见面试题,看看有没有你不会的!
-
你们好,我的网工朋友。网络工程师面试的时候,都会被问到什么?这个问题其实很泛,一般来说,你肯定要先看明白岗位需求写的是什么。基本上都是围绕公司需要的业务去问的。但不可否认的是,那些最基础的概念,多少也...
- 汉得信息:发布EBS系统安装启用JWS的高效解决方案
-
e公司讯,从汉得信息获悉,近日,微软官方宣布InternetExplorer桌面应用程序将于2022年6月15日正式停用。目前大部分客户都是使用IE浏览器打开EBS的Form界面,IE停用后,只能使...
- 36.9K star ! 推荐一个酷炫低代码开发平台!功能太强!
-
前言最近在逛github,看看能不能搜罗到一些对自己有帮助的开源软件。不经意间看到一个高star的java开源项目:jeecg-boot。进入在线演示版一看,感叹实在是太牛了!此开源项目不管是给来学习...
- Linux新手入门系列:Linux下jdk安装配置
-
本系列文章是把作者刚接触和学习Linux时候的实操记录分享出来,内容主要包括Linux入门的一些理论概念知识、Web程序、mysql数据库的简单安装部署,希望能够帮到一些初学者,少走一些弯路。注意:L...
- 手把手教你在嵌入式设备中使用SQLite3
-
摘要:数据库是用来存储和管理数据的专用软件,使得管理数据更加安全,方便和高效。数据库对数据的管理的基本单位是表(table),在嵌入式linux中有时候它也需要用到数据库,听起来好难,其实就是几个函数...
- JAVA语言基础(java语言基础知识)
-
一、计算机的基本概念什么是计算机?计算机(Computer)全称:电子计算机,俗称电脑。是一种能够按照程序运行、自动高速处理海量数据的现代化智能电子设备。由硬件和软件组成、没有安装过任何软件的计算机称...
- 再见 Navicat!一款开源的 Web 数据库管理工具!
-
大家好,我是Java陈序员。在日常的开发工作中,常常需要与各种数据库打交道。而为了提高工作效率,常常会使用一些可视化工具进行操作数据库。今天,给大家介绍一款开源的数据库管理工具,无需下载安装软件,基...
你 发表评论:
欢迎- 一周热门
- 最近发表
-
- 甲骨文签署多项大型云协议,其一未来可贡献超300亿美元年收入
- 甲骨文获TEMU巨额合同,后者大部分基础设施将迁移至Oracle云
- Spring Boot 自定义数据源设置,这些坑你踩过吗?
- 一个开箱即用的代码生成器(一个开箱即用的代码生成器是什么)
- 低代码建模平台-数据挖掘平台(低代码平台的实现方式)
- navicat 17.2.7连接oracle数据库提示加载oracle库失败
- 开源“Windows”ReactOS更新:支持全屏应用
- SSL 推出采用全模拟内置混音技术的模拟调音台Oracle
- 47道网络工程师常见面试题,看看有没有你不会的!
- 汉得信息:发布EBS系统安装启用JWS的高效解决方案
- 标签列表
-
- oracle位图索引 (74)
- oracle批量插入数据 (65)
- oracle事务隔离级别 (59)
- oracle 空为0 (51)
- oracle主从同步 (55)
- oracle 乐观锁 (51)
- redis 命令 (78)
- php redis (88)
- redis 存储 (66)
- redis 锁 (69)
- 启动 redis (66)
- redis 时间 (56)
- redis 删除 (67)
- redis内存 (57)
- redis并发 (52)
- redis 主从 (69)
- redis 订阅 (51)
- redis 登录 (54)
- redis 面试 (58)
- 阿里 redis (59)
- redis 搭建 (53)
- redis的缓存 (55)
- lua redis (58)
- redis 连接池 (61)
- redis 限流 (51)