package com.bizvane.spider.tools;

 import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.jdbc.core.JdbcTemplate; import java.util.HashMap;
import java.util.Map; /**
* Created by Administrator on 2018/1/10.
*/
public class JDBCHelper {
private static Map<String,JdbcTemplate> templateMap = new HashMap<String,JdbcTemplate>(); /**
* 创建连接
*/
public static JdbcTemplate createTemplate(String templateName,
String url, String username, String password,
int initialSize, int maxActive) { BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setInitialSize(initialSize);
dataSource.setMaxActive(maxActive);
JdbcTemplate template = new JdbcTemplate(dataSource);
templateMap.put(templateName, template);
return template;
} /**
* 获取 JdbcTemplate
*/
public static JdbcTemplate getJdbcTemplate(){
String templateName = JdbcConfig.getTemplateName();
String url = JdbcConfig.getUrl();
String username = JdbcConfig.getUsername();
String password = JdbcConfig.getPassword();
int initialSize = (JdbcConfig.getInitialSize()==null)?5:Integer.parseInt(JdbcConfig.getInitialSize());
int maxActive = (JdbcConfig.getMaxActive()==null)?30:Integer.parseInt(JdbcConfig.getMaxActive());
return createTemplate(templateName,url,username,password,initialSize,maxActive);
} /**
* 获取 JdbcTemplate
*/
public static JdbcTemplate getJdbcTemplate(String templateName){
if (templateMap.get(templateName) != null) return templateMap.get(templateName);
JdbcTemplate template = getJdbcTemplate();
templateMap.put(templateName, template);
return template;
} }
05-27 15:40