- 根据传入的数据库信息执行sql
package com.zheytech.common.util; import com.zaxxer.hikari.HikariDataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import java.util.HashMap; import java.util.List; import java.util.Map; public class DataConnectUtil { private static final Logger logger = LoggerFactory.getLogger(DataConnectUtil.class); private static MapsourceMap = new HashMap<>(); //创建DataSource private static HikariDataSource getSource(){ HikariDataSource dataConfig = new HikariDataSource(); dataConfig.setMaximumPoolSize(3); dataConfig.setMinimumIdle(1); dataConfig.setAutoCommit(true); dataConfig.setConnectionTimeout(10000L);//待来自池的连接的最大毫秒数10秒 dataConfig.setMaxLifetime(600000L);//池中连接的最大生存期10分钟 dataConfig.setConnectionTestQuery("SELECt 1 FROM DUAL"); dataConfig.addDataSourceProperty("cachePrepStmts", "true"); dataConfig.addDataSourceProperty("prepStmtCacheSize", "250"); dataConfig.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); dataConfig.setDriverClassName("oracle.jdbc.driver.OracleDriver"); return dataConfig; } //传入数据库相关详细和返回对象,执行sql public static List customDataSource(String id, String url, String username, String password, String query, Class clazz) { HikariDataSource dataConfig = sourceMap.get(id); if(null == sourceMap.get(id)){ dataConfig = getSource(); dataConfig.setJdbcUrl(url); dataConfig.setUsername(username); dataConfig.setPassword(password); sourceMap.put(id, dataConfig); } try { JdbcTemplate dtl = new JdbcTemplate(dataConfig); return dtl.query(query, new BeanPropertyRowMapper<>(clazz)); } catch (Exception e){ e.printStackTrace(); logger.error("数据库连接异常:{}", e.getMessage()); } return null; } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)