方法一:c3p0通过set方法进行配置
1.C3P0下载地址:https://sourceforge.net/projects/c3p0/?source=navbar C3P0是一个开源的连接池。
2.创建c3po.properties配置文件
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/db_c3po
username=root
password=lele112233
3.读取配置文件c3po.properties
/**
* 根据key获取value
* @param key
* @return
*/
public static String getValue(String key) {
//创建一个Properties对象
Properties prop = new Properties();
//读取配置文件c3p0.properties
InputStream in = new PropertiesUtil().getClass().getResourceAsStream("/c3p0.properties");
try {
prop.load(in);
} catch (IOException e) {
e.printStackTrace();
}
return (String)prop.get(key);
}
4.配置DataSource,注入属性
/**
* 配置DataSource,用set方法注入属性
*/
public static ComboPooledDataSource setDataSource(){
ComboPooledDataSource dataSource = new ComboPooledDataSource();
try {
dataSource.setDriverClass(PropertiesUtil.getValue("driverClassName"));
dataSource.setJdbcUrl(PropertiesUtil.getValue("url"));
dataSource.setUser(PropertiesUtil.getValue("username"));
dataSource.setPassword(PropertiesUtil.getValue("password"));
} catch (PropertyVetoException e) {
e.printStackTrace();
}
return dataSource;
}
5.测试连接
//测试连接
public static void main(String[] args) throws SQLException {
try {
Connection C3poConn = setDataSource().getConnection();
System.out.println("连接成功");
System.out.println(C3poConn);
}catch (Exception e) {
System.out.println("连接失败");
}
}
方法二:c3p0通过c3p0-config.xml文件进行配置
1.配置从c3p0-config.xml文件
2.测试连接
读取配置文件进行加载获取dataSource
private static ComboPooledDataSource dataSource = new ComboPooledDataSource("lele");
//测试连接
public static void main(String[] args) throws SQLException {
//ComboPooledDataSource dataSource = new ComboPooledDataSource("lele");
try {
Connection C3poConn = dataSource.getConnection();
System.out.println("连接成功");
System.out.println(C3poConn);
}catch (Exception e) {
System.out.println("连接失败");
}
}