Explorar el Código

初始化数据库接口

xuezizhuo hace 1 año
padre
commit
cc659c5911

+ 1 - 2
ruoyi-admin/src/main/java/com/ruoyi/web/controller/TableInfoController.java

@@ -148,8 +148,7 @@ public class TableInfoController {
      */
     @PostMapping("/initDatabase")
     public AjaxResult initDatabase(@RequestBody DataSource dataSource) {
-        tableInfoService.initDatabase(dataSource);
-        return AjaxResult.success();
+        return tableInfoService.initDatabase(dataSource);
     }
 
 }

+ 24 - 0
ruoyi-common/src/main/java/com/ruoyi/common/constant/LoadDriverConstants.java

@@ -0,0 +1,24 @@
+package com.ruoyi.common.constant;
+
+public class LoadDriverConstants {
+
+    /**
+     * mysql加载驱动
+     */
+    public static final String MYSQL = "com.mysql.cj.jdbc.Driver";
+
+    /**
+     * mysql加载驱动
+     */
+    public static final String SQLSERVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
+
+    /**
+     * mysql加载驱动
+     */
+    public static final String ORACLE = "oracle.jdbc.driver.OracleDriver";
+
+    /**
+     * mysql加载驱动
+     */
+    public static final String DM = "dm.jdbc.driver.DmDriver";
+}

+ 65 - 0
ruoyi-common/src/main/java/com/ruoyi/common/utils/JdbcUtils.java

@@ -0,0 +1,65 @@
+package com.ruoyi.common.utils;
+
+import java.sql.*;
+
+public class JdbcUtils {
+
+    private static final String driver = "com.mysql.cj.jdbc.Driver";
+    private static final String url = "jdbc:mysql://localhost:3306/db1";
+    private static final String name = "root";
+    private static final String password = "root";
+
+    private static final Connection conn;
+
+    static {
+        try {
+            Class.forName(driver);
+            conn = DriverManager.getConnection(url, name, password);
+        } catch (ClassNotFoundException | SQLException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    /**
+     * 获取数据库连接对象
+     * @return 数据库连接对象
+     */
+    public static Connection getConnect() {
+        return conn;
+    }
+
+    /**
+     * 关闭数据库相关资源
+     * @param conn 数据库连接对象
+     * @param ps sql语句执行对象
+     * @param rs 查询结果集
+     */
+    public static void close(Connection conn, PreparedStatement ps, ResultSet rs) {
+        try {
+            if (conn != null) conn.close();
+            if (ps != null) ps.close();
+            if (rs != null) rs.close();
+        } catch (SQLException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    /**
+     * 关闭数据库相关资源
+     * @param conn 数据库连接对象
+     * @param ps sql语句执行对象
+     */
+    public static void close(Connection conn, PreparedStatement ps) {
+        close(conn, ps, null);
+    }
+
+    /**
+     * 关闭数据库相关资源
+     * @param conn 数据库连接对象
+     * @param rs 查询结果集
+     */
+    public static void close(Connection conn, ResultSet rs) {
+        close(conn, null, rs);
+    }
+
+}

+ 5 - 4
ruoyi-common/src/main/java/com/ruoyi/common/utils/datamodeling/DataSourceUtils.java

@@ -2,6 +2,7 @@ package com.ruoyi.common.utils.datamodeling;
 
 import com.ruoyi.common.config.datamodeling.GenConfig;
 import com.ruoyi.common.constant.DataSourceType;
+import com.ruoyi.common.constant.LoadDriverConstants;
 import com.ruoyi.common.core.domain.entity.DataSource;
 
 public class DataSourceUtils {
@@ -14,16 +15,16 @@ public class DataSourceUtils {
         genConfig.setUsername(dataSource.getUsername());
         genConfig.setPassword(dataSource.getPassword());
         if(dataSource.getDatabaseType().equals(DataSourceType.MYSQL.getDataSourceName())){
-            genConfig.setDriverClassName("com.mysql.cj.jdbc.Driver");
+            genConfig.setDriverClassName(LoadDriverConstants.MYSQL);
             genConfig.setUrl("jdbc:mysql://"+dataSource.getDatabaseIp()+":"+dataSource.getPortNumber()+"/"+dataSource.getDatabaseName());
         }else if(dataSource.getDatabaseType().equals(DataSourceType.SQLSERVER.getDataSourceName())){
-            genConfig.setDriverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
+            genConfig.setDriverClassName(LoadDriverConstants.SQLSERVER);
             genConfig.setUrl("jdbc:sqlserver://"+dataSource.getDatabaseIp()+":"+dataSource.getPortNumber()+";DatabaseName="+dataSource.getDatabaseName());
         }else if(dataSource.getDatabaseType().equals(DataSourceType.ORACLE.getDataSourceName())){
-            genConfig.setDriverClassName("oracle.jdbc.driver.OracleDriver");
+            genConfig.setDriverClassName(LoadDriverConstants.ORACLE);
             genConfig.setUrl("jdbc:oracle:thin:@"+dataSource.getDatabaseIp()+":"+dataSource.getPortNumber()+":"+dataSource.getDatabaseName());
         }else if(dataSource.getDatabaseType().equals(DataSourceType.DM.getDataSourceName())){
-            genConfig.setDriverClassName("dm.jdbc.driver.DmDriver");
+            genConfig.setDriverClassName(LoadDriverConstants.DM);
             genConfig.setUrl("jdbc:dm://"+dataSource.getDatabaseIp()+":"+dataSource.getPortNumber()+"?schema="+dataSource.getDatabaseName());
         }
         return genConfig;

+ 1 - 1
zkqy-datamodeling/src/main/java/com/zkqy/datamodeling/service/ITableInfoService.java

@@ -132,5 +132,5 @@ public interface ITableInfoService {
     /**
      * 初始化数据库
      */
-    int initDatabase(DataSource dataSource);
+    AjaxResult initDatabase(DataSource dataSource);
 }

+ 139 - 71
zkqy-datamodeling/src/main/java/com/zkqy/datamodeling/service/impl/TableInfoServiceImpl.java

@@ -2,6 +2,7 @@ package com.zkqy.datamodeling.service.impl;
 
 import com.alibaba.fastjson2.JSON;
 import com.ruoyi.common.constant.DataSourceType;
+import com.ruoyi.common.constant.LoadDriverConstants;
 import com.ruoyi.common.core.domain.AjaxResult;
 import com.ruoyi.common.core.domain.entity.DataSource;
 
@@ -535,81 +536,147 @@ public class TableInfoServiceImpl implements ITableInfoService {
     @Value("${parameter.ip.MAIN_DICTIONARY_IP}")
     private String dictIp;
 
+//    @Override
+//    public int initDatabase(DataSource dataSource) {
+//        RestTemplate restTemplate = new RestTemplate();
+//        // 得到基础模版库的连接信息
+//        String result = restTemplate.getForObject(dictIp + dataSource.getDatabaseType() + "_connection_information", String.class);
+//        Map<String, Object> objectMap = (Map<String, Object>) JSON.parse(result);
+//        List<Map<String, Object>> dictList = (List<Map<String, Object>>) objectMap.get("data");
+//        // 封住基础模版库的信息
+//        DataSource dataSource2 = new DataSource();
+//        try {
+//            aa();
+//            //this.asd();
+//        } catch (Exception e) {
+//            throw new RuntimeException(e);
+//        }
+////        for (Map<String, Object> map : dictList) {
+////            switch (map.get("dictLabel").toString()) {
+////                case "databaseName":
+////                    dataSource2.setDatabaseName(map.get("dictValue").toString());
+////                    break;
+////                case "databaseIp":
+////                    dataSource2.setDatabaseIp(map.get("dictValue").toString());
+////                    break;
+////                case "username":
+////                    dataSource2.setUsername(map.get("dictValue").toString());
+////                    break;
+////                case "password":
+////                    dataSource2.setPassword(map.get("dictValue").toString());
+////                    break;
+////                case "portNumber":
+////                    dataSource2.setPortNumber(Long.parseLong(map.get("dictValue").toString()));
+////                    break;
+////                case "databaseType":
+////                    dataSource2.setDatabaseType(map.get("dictValue").toString());
+////                    break;
+////                // 如果还有其他字段需要处理,可以继续添加case分支
+////                default:
+////                    break;
+////            }
+////        }
+////
+////        // 得到数据源信息 创建连接后进行创建数据库,以及基础数据表
+////        switch (dataSource.getDatabaseType()) {
+////            case "mysql":
+////                // 创建数据库
+////                tableInfoMapper.createMysqlDataBase(dataSource.getDatabaseName());
+////                // 读取基础表信息
+////
+////                // /system/dict/data/type/{dictType}
+////
+////
+////                // 查询主库中字典数据源信息
+////
+////
+////                // 创建所需的基础表
+////                List<String> sd = new ArrayList<>();
+////                tableInfoMapper.createMysqlTable("表名", "表描述", sd);
+////
+////
+////                break;
+////            case "sqlserver":
+////                tableInfoMapper.createSqlServerDataBase(dataSource.getDatabaseName());
+////
+////                // tableInfoMapper.createSqlServerTable();
+////                break;
+////            case "dm":
+////                tableInfoMapper.createDmDataBase(dataSource.getDatabaseName());
+////                break;
+////            case "oracle":
+////                tableInfoMapper.createOracleUser(dataSource.getUsername(), dataSource.getPassword());
+////                break;
+////        }
+//        return 1;
+//    }
+
+
     @Override
-    public int initDatabase(DataSource dataSource) {
-        RestTemplate restTemplate = new RestTemplate();
-        // 得到基础模版库的连接信息
-        String result = restTemplate.getForObject(dictIp + dataSource.getDatabaseType() + "_connection_information", String.class);
-        Map<String, Object> objectMap = (Map<String, Object>) JSON.parse(result);
-        List<Map<String, Object>> dictList = (List<Map<String, Object>>) objectMap.get("data");
-        // 封住基础模版库的信息
-        DataSource dataSource2 = new DataSource();
-        try {
-            aa();
-            //this.asd();
-        } catch (Exception e) {
-            throw new RuntimeException(e);
+    public AjaxResult initDatabase(DataSource dataSource){
+
+        //创建连接
+        Connection con;
+        Statement st;
+        String driverName = null;
+        String dbURL = null;
+        String userName = dataSource.getUsername();;
+        String userPwd = dataSource.getPassword();
+
+        //查询数据库sql
+        String showDatabaseSql = null;
+        //创建数据库
+        String createDatabaseSql = null;
+
+
+        if(dataSource.getDatabaseType().equals(DataSourceType.MYSQL.getDataSourceName())){
+            driverName = LoadDriverConstants.MYSQL;
+            dbURL = "jdbc:mysql://"+dataSource.getDatabaseIp()+":"+dataSource.getPortNumber();
+            showDatabaseSql = "show DATABASES";
+            createDatabaseSql = "CREATE DATABASE IF NOT EXISTS `" + dataSource.getDatabaseName() + "` DEFAULT CHARSET utf8mb4 COLLATE utf8mb4_general_ci;";
+        }else if(dataSource.getDatabaseType().equals(DataSourceType.SQLSERVER.getDataSourceName())){
+            driverName = LoadDriverConstants.SQLSERVER;
+            dbURL = "jdbc:sqlserver://"+dataSource.getDatabaseIp()+":"+dataSource.getPortNumber()+";DatabaseName=;trustServerCertificate=true;";
+            showDatabaseSql = "select name from sys.databases";
+            createDatabaseSql = "CREATE DATABASE "+dataSource.getDatabaseName();
+        }else if(dataSource.getDatabaseType().equals(DataSourceType.DM.getDataSourceName())){
+            driverName = LoadDriverConstants.DM;
+            dbURL = "jdbc:dm://"+dataSource.getDatabaseIp()+":"+dataSource.getPortNumber();
+            showDatabaseSql = "select name from sysobjects where TYPE$='sch' and SUBTYPE$ is null";
+            createDatabaseSql = "CREATE SCHEMA "+dataSource.getDatabaseName();
+        }else if(dataSource.getDatabaseType().equals(DataSourceType.ORACLE.getDataSourceName())){
+            driverName = LoadDriverConstants.ORACLE;
+            dbURL = "jdbc:oracle:thin:@"+dataSource.getDatabaseIp()+":"+dataSource.getPortNumber();
         }
-//        for (Map<String, Object> map : dictList) {
-//            switch (map.get("dictLabel").toString()) {
-//                case "databaseName":
-//                    dataSource2.setDatabaseName(map.get("dictValue").toString());
-//                    break;
-//                case "databaseIp":
-//                    dataSource2.setDatabaseIp(map.get("dictValue").toString());
-//                    break;
-//                case "username":
-//                    dataSource2.setUsername(map.get("dictValue").toString());
-//                    break;
-//                case "password":
-//                    dataSource2.setPassword(map.get("dictValue").toString());
-//                    break;
-//                case "portNumber":
-//                    dataSource2.setPortNumber(Long.parseLong(map.get("dictValue").toString()));
-//                    break;
-//                case "databaseType":
-//                    dataSource2.setDatabaseType(map.get("dictValue").toString());
-//                    break;
-//                // 如果还有其他字段需要处理,可以继续添加case分支
-//                default:
-//                    break;
-//            }
-//        }
-//
-//        // 得到数据源信息 创建连接后进行创建数据库,以及基础数据表
-//        switch (dataSource.getDatabaseType()) {
-//            case "mysql":
-//                // 创建数据库
-//                tableInfoMapper.createMysqlDataBase(dataSource.getDatabaseName());
-//                // 读取基础表信息
-//
-//                // /system/dict/data/type/{dictType}
-//
-//
-//                // 查询主库中字典数据源信息
-//
-//
-//                // 创建所需的基础表
-//                List<String> sd = new ArrayList<>();
-//                tableInfoMapper.createMysqlTable("表名", "表描述", sd);
-//
-//
-//                break;
-//            case "sqlserver":
-//                tableInfoMapper.createSqlServerDataBase(dataSource.getDatabaseName());
-//
-//                // tableInfoMapper.createSqlServerTable();
-//                break;
-//            case "dm":
-//                tableInfoMapper.createDmDataBase(dataSource.getDatabaseName());
-//                break;
-//            case "oracle":
-//                tableInfoMapper.createOracleUser(dataSource.getUsername(), dataSource.getPassword());
-//                break;
-//        }
-        return 1;
+
+        try
+        {
+            Class.forName(driverName); //jdk版本6.0以上可以省略这句话
+            con=DriverManager.getConnection(dbURL,userName,userPwd);
+            st=con.createStatement();
+
+            //查询所有数据库
+            ResultSet rs = st.executeQuery(showDatabaseSql);
+            while(rs.next()){//如果对象中有数据,就会循环打印出来
+                System.out.println(rs.getString(1));
+                if(rs.getString(1).equals(dataSource.getDatabaseName())){
+                    return AjaxResult.warn("数据库已存在!");
+                }
+            }
+
+            //创建数据库
+            st.executeUpdate(createDatabaseSql);
+
+        }catch(Exception e)
+        {
+            e.printStackTrace();
+        }
+
+
+        return AjaxResult.success();
     }
 
+
     public static void asd() throws Exception {
         //Class.forName("dm.jdbc.driver.DmDriver");
         Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
@@ -639,6 +706,7 @@ public class TableInfoServiceImpl implements ITableInfoService {
         }
     }
 
+    //创建数据库
     public void aa() throws Exception{
         Connection con;
         Statement st;