package com.product.data.sync.util; import com.product.core.config.Global; import com.product.core.exception.BaseException; import com.product.core.spring.context.SpringMVCContextHolder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Component; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; /** * @Author cheng * @Date 2022/1/18 15:09 * @Desc 获取当前数据库连接 */ public class ConnectionManager { private static ConnectionManager connectionManager = new ConnectionManager(); private String url; private String userName; private String password; private String driver; private String databaseType; public ConnectionManager() { System.out.println(this); this.url = Global.getSystemConfig("data.source.url", ""); this.userName = Global.getSystemConfig("data.source.user", ""); this.password = Global.getSystemConfig("data.source.password", ""); this.driver = Global.getSystemConfig("data.source.driver", ""); this.databaseType = Global.getSystemConfig("data.source.type", ""); } /** * 获取jdbc连接 * * @param diver jdbc连接类型 * @param jdbc 连接url * @param user 用户名 * @param pwd 密码 * @return JDBC连接 * @throws BaseException */ public static Connection getConnection(String diver, String jdbc, String user, String pwd) throws BaseException { try { Class.forName(diver); Connection connection = DriverManager.getConnection(jdbc, user, pwd); return connection; } catch (Exception e) { SpringMVCContextHolder.getSystemLogger().error(e); throw new BaseException(e); } } /** * 获取数据库连接 * * @return * @throws BaseException */ public final static Connection getConnection() throws BaseException { try { Class.forName(connectionManager.driver); return DriverManager.getConnection(connectionManager.url, connectionManager.userName, connectionManager.password); } catch (SQLException | ClassNotFoundException e) { throw new BaseException(e); } } }