Browse Source

获取数据库表信息

3254194295 3 tháng trước cách đây
mục cha
commit
a8af11b092

+ 71 - 0
platform-rest/src/main/java/com/platform/rest/controller/workflow/DatabaseController.java

@@ -0,0 +1,71 @@
+package com.platform.rest.controller.workflow;
+
+import com.alibaba.fastjson.JSONObject;
+import com.google.gson.JsonObject;
+import com.platform.common.bean.AbstractPageResultBean;
+import com.platform.common.exception.BusinessException;
+import com.platform.common.util.BeanConverterUtil;
+import com.platform.common.util.R;
+import com.platform.common.validation.group.AddGroup;
+import com.platform.common.validation.group.UpdateGroup;
+import com.platform.dao.dto.workflow.WorkflowConditionSwitchDTO;
+import com.platform.dao.entity.workflow.WorkflowConditionSwitch;
+import com.platform.dao.util.ExcelUtil;
+import com.platform.dao.vo.export.workflow.ExportWorkflowConditionSwitchVO;
+import com.platform.dao.vo.query.workflow.WorkflowConditionSwitchVO;
+import com.platform.rest.log.annotation.SysLog;
+import com.platform.service.util.DatabaseUtil;
+import com.platform.service.workflow.WorkflowConditionSwitchService;
+import lombok.AllArgsConstructor;
+import org.springframework.security.access.prepost.PreAuthorize;
+import org.springframework.util.unit.DataUnit;
+import org.springframework.validation.annotation.Validated;
+import org.springframework.web.bind.annotation.*;
+
+import javax.servlet.http.HttpServletResponse;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * @Description 流程审核条件分支表 控制器
+ * @Author lsq
+ * @Date 2024-06-03 17:01:58
+ * @Version Copyright (c) 2020,北京乾元坤和科技有限公司 All rights reserved.
+ */
+@RestController
+@AllArgsConstructor
+@RequestMapping("/database/data")
+public class DatabaseController {
+
+
+
+    /**
+     * 通过id查询单条记录
+     *
+     * @param tableName 主键
+     * @return R
+     */
+    @GetMapping("/getTableInfos/{tableName}")
+    public R getTableInfos(@PathVariable("tableName") String tableName) {
+        if (tableName==null){
+            throw new BusinessException("表名为空!");
+        }
+        List<String> columnNames = DatabaseUtil.getColumnNames(tableName);
+        List<String> columnComments = DatabaseUtil.getColumnComments(tableName);
+        List<JSONObject> list = new ArrayList<>();
+        for (int i = 0;i<columnNames.size();i++){
+            for (int j = 0;j<columnComments.size();j++){
+                if (i==j){
+                    JSONObject jsonObject = new JSONObject();
+                    jsonObject.put("columnName",columnNames.get(i));
+                    jsonObject.put("columnComment",columnComments.get(j));
+                    list.add(jsonObject);
+                    break;
+                }
+            }
+        }
+        return new R<>(list);
+    }
+
+
+}

+ 200 - 0
platform-service/src/main/java/com/platform/service/util/DatabaseUtil.java

@@ -0,0 +1,200 @@
+package com.platform.service.util;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.sql.*;
+import java.util.ArrayList;
+import java.util.List;
+
+public class DatabaseUtil {
+    private final static Logger LOGGER = LoggerFactory.getLogger(DatabaseUtil.class);
+
+    private static final String DRIVER = "com.mysql.cj.jdbc.Driver";
+    private static final String URL = "jdbc:mysql://123.60.19.203:5006/hitch-sb-demo?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=GMT%2B8&autoReconnect=true&allowMultiQueries=true&removeAbandoned=true&removeAbandonedTimeout=60&logAbandoned=true";
+    private static final String USERNAME = "root";
+    private static final String PASSWORD = "mysql?MYSQLmoniu123";
+
+    private static final String SQL = "SELECT * FROM ";// 数据库操作
+
+    static {
+        try {
+            Class.forName(DRIVER);
+        } catch (ClassNotFoundException e) {
+            LOGGER.error("can not load jdbc driver", e);
+        }
+    }
+
+    /**
+     * 获取数据库连接
+     *
+     * @return
+     */
+    public static Connection getConnection() {
+        Connection conn = null;
+        try {
+            conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
+        } catch (SQLException e) {
+            LOGGER.error("get connection failure", e);
+        }
+        return conn;
+    }
+
+    /**
+     * 关闭数据库连接
+     * @param conn
+     */
+    public static void closeConnection(Connection conn) {
+        if(conn != null) {
+            try {
+                conn.close();
+            } catch (SQLException e) {
+                LOGGER.error("close connection failure", e);
+            }
+        }
+    }
+
+    /**
+     * 获取数据库下的所有表名
+     */
+    public static List<String> getTableNames() {
+        List<String> tableNames = new ArrayList<>();
+        Connection conn = getConnection();
+        ResultSet rs = null;
+        try {
+            //获取数据库的元数据
+            DatabaseMetaData db = conn.getMetaData();
+            System.out.println("conn.getCatalog() = " + conn.getCatalog());
+            //从元数据中获取到所有的表名
+            rs = db.getTables(conn.getCatalog(), null, null, new String[] { "TABLE" });
+            while(rs.next()) {
+            	String tableName = (String) rs.getObject("TABLE_NAME");
+                System.out.println("tableName:" + tableName);
+                tableNames.add(rs.getString(3));
+            }
+        } catch (SQLException e) {
+            LOGGER.error("getTableNames failure", e);
+        } finally {
+            try {
+                rs.close();
+                closeConnection(conn);
+            } catch (SQLException e) {
+                LOGGER.error("close ResultSet failure", e);
+            }
+        }
+        return tableNames;
+    }
+
+    /**
+     * 获取表中所有字段名称
+     * @param tableName 表名
+     * @return
+     */
+    public static List<String> getColumnNames(String tableName) {
+        List<String> columnNames = new ArrayList<>();
+        //与数据库的连接
+        Connection conn = getConnection();
+        PreparedStatement pStemt = null;
+        String tableSql = SQL + tableName;
+        try {
+            pStemt = conn.prepareStatement(tableSql);
+            //结果集元数据
+            ResultSetMetaData rsmd = pStemt.getMetaData();
+            //表列数
+            int size = rsmd.getColumnCount();
+            for (int i = 0; i < size; i++) {
+                columnNames.add(rsmd.getColumnName(i + 1));
+            }
+        } catch (SQLException e) {
+            LOGGER.error("getColumnNames failure", e);
+        } finally {
+            if (pStemt != null) {
+                try {
+                    pStemt.close();
+                    closeConnection(conn);
+                } catch (SQLException e) {
+                    LOGGER.error("getColumnNames close pstem and connection failure", e);
+                }
+            }
+        }
+        return columnNames;
+    }
+
+    /**
+     * 获取表中所有字段类型
+     * @param tableName
+     * @return
+     */
+    public static List<String> getColumnTypes(String tableName) {
+        List<String> columnTypes = new ArrayList<>();
+        //与数据库的连接
+        Connection conn = getConnection();
+        PreparedStatement pStemt = null;
+        String tableSql = SQL + tableName;
+        try {
+            pStemt = conn.prepareStatement(tableSql);
+            //结果集元数据
+            ResultSetMetaData rsmd = pStemt.getMetaData();
+            //表列数
+            int size = rsmd.getColumnCount();
+            for (int i = 0; i < size; i++) {
+                columnTypes.add(rsmd.getColumnTypeName(i + 1));
+            }
+        } catch (SQLException e) {
+            LOGGER.error("getColumnTypes failure", e);
+        } finally {
+            if (pStemt != null) {
+                try {
+                    pStemt.close();
+                    closeConnection(conn);
+                } catch (SQLException e) {
+                    LOGGER.error("getColumnTypes close pstem and connection failure", e);
+                }
+            }
+        }
+        return columnTypes;
+    }
+
+    /**
+     * 获取表中字段的所有注释
+     * @param tableName
+     * @return
+     */
+    public static List<String> getColumnComments(String tableName) {
+        List<String> columnTypes = new ArrayList<>();
+        //与数据库的连接
+        Connection conn = getConnection();
+        PreparedStatement pStemt = null;
+        String tableSql = SQL + tableName;
+        List<String> columnComments = new ArrayList<>();//列名注释集合
+        ResultSet rs = null;
+        try {
+            pStemt = conn.prepareStatement(tableSql);
+            rs = pStemt.executeQuery("show full columns from " + tableName);
+            while (rs.next()) {
+                columnComments.add(rs.getString("Comment"));
+            }
+        } catch (SQLException e) {
+            e.printStackTrace();
+        } finally {
+            if (rs != null) {
+                try {
+                    rs.close();
+                    closeConnection(conn);
+                } catch (SQLException e) {
+                    LOGGER.error("getColumnComments close ResultSet and connection failure", e);
+                }
+            }
+        }
+        return columnComments;
+    }
+    public static void main(String[] args) {
+        List<String> tableNames = getTableNames();
+        System.out.println("tableNames:" + tableNames);
+        for (String tableName : tableNames) {
+            System.out.println("ColumnNames:" + getColumnNames("t_sb_info"));
+            System.out.println("ColumnTypes:" + getColumnTypes("t_sb_info"));
+            System.out.println("ColumnComments:" + getColumnComments("t_sb_info"));
+        }
+    }
+}