通过java代码连接数据库,利用HikariDataSource动态连接池的方式连接数据库且执行sql语句。

包含3个数据库连接池的配置类,一个使用方法。

配置类1:数据源实体类:

import java.io.Serializable;

/**
 * @description: DataSourceInfo 数据源信息
 **/
public class DataSourceInfo implements Serializable {
    /**主键**/
    private String id_;
    //数据源Code 连接池绑定ID
    private String dataSourceCode;
    //数据源别名
    private String dataSourceName;
    //数据源类型
    private String databaseType;
    //数据库连接驱动
    private String driver;
    //数据库连接
    private String dataSourceUrl;
    //用户名
    private String username;
    //用户密码
    private String password;

    public String getId_() {
        return id_;
    }

    public void setId_(String id_) {
        this.id_ = id_;
    }

    public String getDataSourceName() {
        return dataSourceName;
    }

    public void setDataSourceName(String dataSourceName) {
        this.dataSourceName = dataSourceName;
    }

    public String getDatabaseType() {
        return databaseType;
    }

    public void setDatabaseType(String databaseType) {
        this.databaseType = databaseType;
    }

    public String getDriver() {
        return driver;
    }

    public void setDriver(String driver) {
        this.driver = driver;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getDataSourceCode() {
        return dataSourceCode;
    }

    public void setDataSourceCode(String dataSourceCode) {
        this.dataSourceCode = dataSourceCode;
    }

    public String getDataSourceUrl() {
        return dataSourceUrl;
    }

    public void setDataSourceUrl(String dataSourceUrl) {
        this.dataSourceUrl = dataSourceUrl;
    }
}

配置类2:动态连接池类:

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * @description: DynamicDataSourcePool 动态连接池类
 **/
public class DynamicDataSourcePool {

    private static final Logger log = LoggerFactory.getLogger(DynamicDataSourcePool.class);
    /**
     *     申明HikariCP数据连接池变量
     */
    private HikariDataSource pool = null;

    /**
     * 默认的构造方法
     * @param poolName    连接池名称
     * @param userName    数据库用户名
     * @param pass        数据库密码
     * @param url         连接的url
     * @param driverClass 数据驱动
     */
    public DynamicDataSourcePool(String poolName, String userName, String pass, String url, String driverClass) {
        try {
            //创建对象
            HikariConfig hikariConfig = new HikariConfig();
            //连接池中保留的最大连接数
            hikariConfig.setMaximumPoolSize(100);
            //设置驱动
            hikariConfig.setDriverClassName(driverClass);
            //设置连接的url
            hikariConfig.setJdbcUrl(url);
            //设置数据库用户名
            hikariConfig.setUsername(userName);
            //设置数据库密码
            hikariConfig.setPassword(pass);
            //创建初始化连接池
            //设置连接池名称
            hikariConfig.setPoolName("Hikari-" + poolName);
            this.pool = new HikariDataSource(hikariConfig);
            log.info("数据库连接池初始化成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 得到连接
     *
     * @return Connection
     */
    public Connection getConnection() {
        try {
            return this.pool.getConnection();
        } catch (SQLException e) {
            log.info("获取连接异常");
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 关闭
     */
    public void destroy() {
        if (null != this.pool) {
            this.pool.close();
        }
    }
}

配置类3:连接池管理类

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @description: DynamicDataSourcePoolFactory 连接池的管理类
 **/
public class DynamicDataSourcePoolFactory {

    private static final Logger log = LoggerFactory.getLogger(DynamicDataSourcePoolFactory.class);
    //存储连接池数据
    private static ConcurrentHashMap<String, DynamicDataSourcePool> poolConcurrentHashMap = null;
    //连接池管理类
    private static DynamicDataSourcePoolFactory dataSourcePoolFactory;

    public DynamicDataSourcePoolFactory() {

    }

    public static DynamicDataSourcePoolFactory getInstance() {
        if (null == dataSourcePoolFactory) {
            poolConcurrentHashMap = new ConcurrentHashMap<String, DynamicDataSourcePool>();
            dataSourcePoolFactory = new DynamicDataSourcePoolFactory();
        }
        return dataSourcePoolFactory;
    }

    /**
     * 绑定连接池
     *
     * @param key            连接池的名称必须唯一
     * @param dataSourcePool 对应的连接池
     */
    public void bind(String key, DynamicDataSourcePool dataSourcePool) {
        if (IsBePool(key)) {
            getDynamicDataSourcePool(key).destroy();
        }
        poolConcurrentHashMap.put(key, dataSourcePool);
    }

    /**
     * 重新绑定连接池
     *
     * @param key            连接池的名称必须唯一
     * @param dataSourcePool 对应的连接池
     */
    public void rebind(String key, DynamicDataSourcePool dataSourcePool) {
        if (IsBePool(key)) {
            getDynamicDataSourcePool(key).destroy();
        }
        poolConcurrentHashMap.put(key, dataSourcePool);
    }

    /**
     * 删除动态数据连接池中名称为key的连接池
     *
     * @param key 连接池的名称必须唯一
     */
    public void unbind(String key) {
        if (IsBePool(key)) {
            getDynamicDataSourcePool(key).destroy();
        }
        poolConcurrentHashMap.remove(key);
    }

    /**
     * 查找动态数据连接池中是否存在名称为key的连接池
     *
     * @param key 连接池的名称必须唯一
     * @return boolean
     */
    public boolean IsBePool(String key) {
        return poolConcurrentHashMap.containsKey(key);
    }

    /**
     * 根据key返回key对应的连接池
     *
     * @param key 连接池的名称必须唯一
     * @return DynamicDataSourcePool
     */
    public DynamicDataSourcePool getDynamicDataSourcePool(String key) {
        if (!IsBePool(key)) {
            return null;
        }
        return (DynamicDataSourcePool) poolConcurrentHashMap.get(key);

    }

    /**
     * 获取数据库连接
     *
     * @param dataSource dataSource
     * @return
     */
    public Connection getConnection(DataSourceInfo dataSource) {
        if (StringUtils.isBlank(dataSource.getDataSourceCode().trim())) {
            return null;
        }
        Connection conn;
        if (!DynamicDataSourcePoolFactory.getInstance().IsBePool(dataSource.getDataSourceCode().trim())) {
            buildDataSourcePool(dataSource);
        }
        DynamicDataSourcePool dynamicDataSourcePool = DynamicDataSourcePoolFactory.getInstance().getDynamicDataSourcePool(dataSource.getDataSourceCode().trim());
        conn = dynamicDataSourcePool.getConnection();
        return conn;
    }

    public static String buildDataSourcePool(DataSourceInfo dataSource) {
        if (dataSource == null) {
            return "数据源对象为 null,请检查数据库";
        }
        //判断 数据库驱动、数据库连接、数据库用户名不为空  密码可为空
        if (StringUtils.isBlank(dataSource.getDataSourceCode()) || StringUtils.isBlank(dataSource.getDriver()) || StringUtils.isBlank(dataSource.getDataSourceUrl()) || StringUtils.isBlank(dataSource.getUsername())) {
            log.info("================================================================");
            log.info("Error:Database configuration in the support library is incomplete");
            return "Error:Database configuration in the support library is incomplete";
        }
        DynamicDataSourcePoolFactory factory = DynamicDataSourcePoolFactory.getInstance();

        if (factory.IsBePool(dataSource.getDataSourceCode().trim())) {
            return "Info:The data source already exists:" + dataSource.getDataSourceCode().trim();
        }

        DynamicDataSourcePool dataSourcePool = new DynamicDataSourcePool(dataSource.getDataSourceCode(), dataSource.getUsername().trim(),
                dataSource.getPassword().trim(),
                dataSource.getDataSourceUrl().trim(), dataSource.getDriver().trim());
        //数据源连接池绑定
        factory.bind(dataSource.getDataSourceCode().trim(), dataSourcePool);
        //判断数据库连接池是否注册成功
        if (factory.IsBePool(dataSource.getDataSourceCode().trim())) {
            log.info("Success:Successfully registered a new database connection pool:" + dataSource.getDataSourceCode().trim());
            return "Success:Successfully registered a new database connection pool:" + dataSource.getDataSourceCode().trim();
        } else {
            log.info("Error:Failed to register a new database connection pool:" + dataSource.getDataSourceCode().trim());
            return "Error:Failed to register a new database connection pool:" + dataSource.getDataSourceCode().trim();
        }
    }

    //获得连接 Connection conn = DynamicDataSourcePoolFactory.getInstance().getConnection(DataSource.getName());
}

使用方法:

    @PostMapping("/connectionPool")
    public AjaxResult connectionPool(@RequestBody DataSourceInfo dataSourceInfo, @RequestParam(value = "sqlStr") String sqlStr){
        try {
            Connection conn = null;
            Statement stmt = null;
            List<LinkedHashMap<String, Object>> table = null;
            try {
                conn = DynamicDataSourcePoolFactory.getInstance().getConnection(dataSourceInfo);
                stmt = conn.createStatement();
                stmt.setQueryTimeout(180);
                table = new ArrayList<>();
                ResultSet resultSet = stmt.executeQuery(sqlStr);
                if (null != resultSet){
                    while (resultSet.next()){
                        ResultSetMetaData rsmd = resultSet.getMetaData();
                        int columnCount = rsmd.getColumnCount();
                        LinkedHashMap<String, Object> row = new LinkedHashMap<>();
                        for (int i = 1; i <= columnCount; i++) {
                            Object colValue = resultSet.getObject(i);
                            row.put(rsmd.getColumnName(i), colValue);
                        }
                        table.add(row);
                    }
                }
            }catch (SQLException e){
                e.printStackTrace();
                throw new SQLException(e.getMessage());
            }finally {
                try {
                    if (null != stmt) {
                        stmt.close();
                    }
                    if (null != conn) {
                        conn.close();
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            return AjaxResult.success(table);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("连接池接口异常:" + ExceptionUtils.getMessage(e));
        }
    }

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值