SpringMVC,SpringBoot框架 JdbcTemplate的使用方法
import java.util.HashMap;
import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class JDBCHelper {
public static HashMap<String, JdbcTemplate> templateMap = new HashMap<String, JdbcTemplate>();
public static JdbcTemplate createMysqlTemplate(String templateName, String url, String username, String password, int initialSize, int maxActive) {
BasicDataSource dataSource = new BasicDataSource();
// dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setDriverClassName("org.mariadb.jdbc.Driver");
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setInitialSize(initialSize);
dataSource.setMaxActive(maxActive);
dataSource.setMaxWait(60000);
dataSource.setValidationQuery("select 1");
dataSource.setTestWhileIdle(true);//指明连接是否被空闲连接回收器(如果有)进行检验.如果检测失败,则连接将被从池中去除.
dataSource.setTestOnBorrow(true); //每次获取一个连接的时候,验证一下连接是否可用,语句在validationQuery里面
dataSource.setTimeBetweenEvictionRunsMillis(300000);//在空闲连接回收器线程运行期间休眠的时间值,以毫秒为单位,一般比minEvictableIdleTimeMillis小
dataSource.setMinEvictableIdleTimeMillis(1800000);
// dataSource.setRemoveAbandoned(true);//自动处理连接未关闭的问题
// dataSource.setRemoveAbandonedTimeout(300);//连接使用后5分钟未关闭,则抛弃
dataSource.setNumTestsPerEvictionRun(maxActive); //在每次空闲连接回收器线程(如果有)运行时检查的连接数量,最好和maxActive一致
JdbcTemplate template = new JdbcTemplate(dataSource);
templateMap.put(templateName, template);
return template;
}
public static JdbcTemplate getJdbcTemplate(String templateName){
return templateMap.get(templateName);
}
}
调用JdbcTemplate方法:
JDBCHelper.createMysqlTemplate("temp_alibaba", "jdbc:mysql://127.0.0.1:3306/数据库?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8", "用户名", "密码", 5, 20);
注意:本文归作者所有,未经作者允许,不得转载