package checkwords;


import java.sql.Connection;

import java.sql.DatabaseMetaData;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.ResultSetMetaData;

import java.sql.Statement;


public class CheckSensitiveWords {

    public static void main(String[] args) {

//        String jdbcUrl = "jdbc:sqlserver://*****;databaseName=***;encrypt=false";

        String jdbcUrl = "jdbc:mysql://localhost:1433;databaseName=mysql;encrypt=false";

//        String username = "sa";

//        String password = "8888";

      String username = "root";

      String password = "root";

        String[] sensitiveWords = {"返利", "敏感词2", "敏感词3"};


        try {

            // 连接到SQL Server数据库

            Connection connection = DriverManager.getConnection(jdbcUrl, username, password);


            // 获取数据库元数据

            DatabaseMetaData metaData = connection.getMetaData();


            // 获取所有表的名称

            ResultSet tables = metaData.getTables(null, null, null, new String[]{"TABLE"});


            while (tables.next()) {

                String tableName = tables.getString("TABLE_NAME");

                //System.out.println("检查表 " + tableName + " 中是否包含敏感词:");


                // 获取表的元数据,包括字段信息

                ResultSet columns = metaData.getColumns(null, null, tableName, null);

                Statement statement = connection.createStatement();


                while (columns.next()) {

                    String columnName = columns.getString("COLUMN_NAME");

                    String dataType = columns.getString("TYPE_NAME");


                    // 仅处理字符串类型的字段

                    if ("VARCHAR".equalsIgnoreCase(dataType) || "NVARCHAR".equalsIgnoreCase(dataType)) {

                        // 构建查询语句

                        String query = "SELECT * FROM " + tableName + " WHERE " + columnName + " LIKE ?";

                        PreparedStatement preparedStatement = connection.prepareStatement(query);


                        // 遍历敏感词列表并执行查询

                        for (String sensitiveWord : sensitiveWords) {

                            preparedStatement.setString(1, "%" + sensitiveWord + "%");

                            ResultSet resultSet = preparedStatement.executeQuery();


                            // 输出包含敏感词的行

                            while (resultSet.next()) {

                                String value = resultSet.getString(columnName);

                                System.out.println("表 " + tableName + " 字段 " + columnName + " 中包含敏感词 '" + sensitiveWord + "': " + value);

                            }

                        }

                    }

                }

            }

            connection.close();

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

}