import lombok.Data; import lombok.SneakyThrows; import org.springframework.util.StringUtils; import java.sql.Connection; import java.sql.Driver; import java.sql.DriverManager; public class JdbcDriverManger { @SneakyThrows public static Connection connection(JdbcDriverEnum jdbcDriverEnum, String jdbcUrl, String user, String password, String database) { if (!StringUtils.hasText(jdbcUrl)) { throw new NullPointerException("数据库连接不能为空"); } Class<?> aClass = Class.forName(jdbcDriverEnum.getValue()); Driver driver = (Driver) aClass.newInstance(); DriverManager.deregisterDriver(driver); if (!StringUtils.hasText(database)) { jdbcUrl = jdbcUrl + "/" + database; } return DriverManager.getConnection(jdbcUrl, user, password); } public static Connection createConnect(DataBaseInfo dataBaseInfo, String database) { String jdbcUrl = ""; JdbcDriverEnum jdbcDriverEnum = null; switch (dataBaseInfo.getSourceType()) { case 1: jdbcUrl = "jdbc:mysql://"; jdbcDriverEnum = JdbcDriverEnum.MYSQL5; break; case 2: jdbcUrl = "jdbc:clickhouse://"; jdbcDriverEnum = JdbcDriverEnum.CLICKHOUSE; break; case 3: jdbcUrl = "jdbc:oracle:thin:@"; jdbcDriverEnum = JdbcDriverEnum.ORACLE; break; case 4: jdbcUrl = "jdbc:postgresql://"; jdbcDriverEnum = JdbcDriverEnum.POSTGRESQL; break; } jdbcUrl = jdbcUrl + dataBaseInfo.getIpAddress() +":"+ dataBaseInfo.getPort(); if (dataBaseInfo.getSourceType() == 1&& StringUtils.hasText(database)){ jdbcUrl += "?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowMultiQueries=true"; }else if (dataBaseInfo.getSourceType() == 1 && !StringUtils.hasText(database)){ database += "?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowMultiQueries=true"; } return JdbcDriverManger.connection(jdbcDriverEnum, jdbcUrl, dataBaseInfo.getUser(), dataBaseInfo.getPassword(), database); } } @Data class DataBaseInfo { private int sourceType; private String sourceId; private String user; private String password; private String ipAddress; private String port; }
注意:pom中需要引入对应的连接驱动
标签:DriverManager,dataBaseInfo,java,String,database,数据源,jdbcDriverEnum,JdbcDriverEnu From: https://www.cnblogs.com/goPush/p/17420642.html