亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Java使用screw來對比數(shù)據(jù)庫表和字段差異

 更新時(shí)間:2024年12月18日 08:28:13   作者:Harries?Blog  
這篇文章主要介紹了Java如何使用screw來對比數(shù)據(jù)庫表和字段差異,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下

1.Screw 庫簡介

Screw 是一個(gè)用于數(shù)據(jù)庫結(jié)構(gòu)分析和文檔生成的 Java 庫。它支持多種數(shù)據(jù)庫,包括 MySQL、PostgreSQL 和 Oracle。Screw 可以幫助開發(fā)者快速獲取數(shù)據(jù)庫的表結(jié)構(gòu)、字段信息,并進(jìn)行比較。

2.原理

使用 Screw 庫對比數(shù)據(jù)庫表和字段的基本原理如下:

  • 連接數(shù)據(jù)庫:使用 JDBC 連接到需要對比的兩個(gè)數(shù)據(jù)庫。
  • 獲取表結(jié)構(gòu):使用 Screw 提供的 API 獲取每個(gè)數(shù)據(jù)庫中的表和字段信息。
  • 比較表和字段:將兩個(gè)數(shù)據(jù)庫的表和字段信息進(jìn)行比較,識別出存在的差異。
  • 生成報(bào)告:將比較結(jié)果生成報(bào)告,方便后續(xù)查看和分析。

3.環(huán)境搭建

第一個(gè)mysql數(shù)據(jù)庫

docker run --name docker-mysql -e MYSQL_ROOT_PASSWORD=123456 -p 3306:3306 -d mysql

初始化數(shù)據(jù)

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.代碼工程

目標(biāo)

使用 Screw 庫對比兩個(gè) MySQL 數(shù)據(jù)庫表和字段

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());
            }
        }
    }
}

代碼解析

  • 數(shù)據(jù)庫連接配置:使用 HikariCP 配置數(shù)據(jù)庫連接信息,包括數(shù)據(jù)庫 URL、用戶名和密碼。
  • 獲取表結(jié)構(gòu):通過 query.getTables() 方法獲取數(shù)據(jù)庫中的表信息。
  • 比較表:將兩個(gè)數(shù)據(jù)庫的表信息存儲在 Map 中,并進(jìn)行比較,輸出存在于一個(gè)數(shù)據(jù)庫但不存在于另一個(gè)數(shù)據(jù)庫的表。
  • 比較字段:在比較表的同時(shí),調(diào)用 compareColumns 方法獲取字段信息,并進(jìn)行比較,輸出字段的存在性和類型差異。

以上只是一些關(guān)鍵代碼,所有代碼請參見下面代碼倉庫

代碼倉庫

https://github.com/Harries/springboot-demo(screw)

5.測試

運(yùn)行測試類的main方法,將結(jié)果寫入word文檔

到此這篇關(guān)于Java使用screw來對比數(shù)據(jù)庫表和字段差異的文章就介紹到這了,更多相關(guān)Java screw對比數(shù)據(jù)庫表和字段差異內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Java應(yīng)用打包后運(yùn)行需要注意編碼問題

    Java應(yīng)用打包后運(yùn)行需要注意編碼問題

    這篇文章主要介紹了 Java應(yīng)用打包后運(yùn)行需要注意編碼問題的相關(guān)資料,需要的朋友可以參考下
    2016-12-12
  • 淺談java中OO的概念和設(shè)計(jì)原則(必看)

    淺談java中OO的概念和設(shè)計(jì)原則(必看)

    下面小編就為大家?guī)硪黄獪\談java中OO的概念和設(shè)計(jì)原則(必看)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-05-05
  • 解決springboot responseentity<string>亂碼問題

    解決springboot responseentity<string>亂碼問題

    這篇文章主要介紹了解決springboot responseentity<string>亂碼問題,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-07-07
  • java中實(shí)現(xiàn)token過期失效超時(shí)

    java中實(shí)現(xiàn)token過期失效超時(shí)

    在Java應(yīng)用程序中,為了確保安全性和保護(hù)用戶數(shù)據(jù),一種常見的做法是使用Token進(jìn)行身份驗(yàn)證和授權(quán),Token是由服務(wù)器生成的具有一定時(shí)效的令牌,用于識別和驗(yàn)證用戶身份,當(dāng)Token失效后,用戶將無法再進(jìn)行相關(guān)操作,從而提高系統(tǒng)的安全性
    2023-10-10
  • Java?ASM使用logback日志級別動態(tài)切換方案展示

    Java?ASM使用logback日志級別動態(tài)切換方案展示

    這篇文章主要介紹了Java?ASM使用logback日志級別動態(tài)切換方案展示,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步早日升職加薪
    2022-04-04
  • java實(shí)現(xiàn)直線分形山脈

    java實(shí)現(xiàn)直線分形山脈

    這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)直線分形山脈,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-01-01
  • Java中的CountDownLatch原理深入解析

    Java中的CountDownLatch原理深入解析

    這篇文章主要介紹了Java中的CountDownLatch原理深入解析,CountDownLatch是多線程控制的一種同步工具類,它被稱為門閥、 計(jì)數(shù)器或者閉鎖,這個(gè)工具經(jīng)常用來用來協(xié)調(diào)多個(gè)線程之間的同步,或者說起到線程之間的通信,需要的朋友可以參考下
    2024-01-01
  • Java中的Socket編程使用方法詳解

    Java中的Socket編程使用方法詳解

    這篇文章主要介紹了Java中的Socket編程使用的相關(guān)資料,文中詳細(xì)講解了Socket的基本概念、Java中Socket的使用方法以及客戶端與服務(wù)器之間的簡單通信示例,需要的朋友可以參考下
    2024-12-12
  • java正則表達(dá)式校驗(yàn)日期格式實(shí)例代碼

    java正則表達(dá)式校驗(yàn)日期格式實(shí)例代碼

    如果使用得當(dāng),正則表達(dá)式是匹配各種模式的強(qiáng)大工具,下面這篇文章主要給大家介紹了關(guān)于java正則表達(dá)式校驗(yàn)日期格式的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2023-05-05
  • Java 淺談 高并發(fā) 處理方案詳解

    Java 淺談 高并發(fā) 處理方案詳解

    這篇文章主要介紹了淺談Java高并發(fā)解決方案以及高負(fù)載優(yōu)化方法,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-09-09

最新評論