一、C3P0
导入jar包(c3p0-0.9.1.2.jar)
配置c3p0-config.xml(名称固定)
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<default-config>
<property name="driverClass">com.mysql.cj.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3307/user?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Hongkong</property>
<property name="user">root</property>
<property name="password">123456</property>
<property name="initialPoolSize">5</property>
<property name="maxPoolSize">20</property>
</default-config>
<named-config name="xf">
<property name="driverClass">com.mysql.cj.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3307/user?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Hongkong</property>
<property name="user">root</property>
<property name="password">123456</property>
</named-config>
</c3p0-config>
注意:配置jdbcuUrl时用&替代&
3. 编写工具类C3P0
public class C3P0Utils {
private static ComboPooledDataSource dataSource = new ComboPooledDataSource("xf");
public static ComboPooledDataSource getDataSource() {
return dataSource;
}
public static Connection getConnection(){
try {
return dataSource.getConnection();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
二、DBCP
- 导入jar包(commons-dbcp-1.4.jar和commons-pool-1.5.6.jar)
- 配置db.properties
如何设置参考http://commons.apache.org/proper/commons-dbcp/configuration.html
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3307/user
connectionProperties=useUnicode=true;characterEncoding=utf8;useSSL=false;serverTimezone=Hongkong
username=root
password=123456
- 编写工具类
public class DBCPUtils {
private static DataSource dataSource;
static {
ClassLoader classLoader = DBCPUtils.class.getClassLoader();
InputStream is = classLoader.getResourceAsStream("db.properties");
Properties props = new Properties();
try {
props.load(is);
dataSource = BasicDataSourceFactory.createDataSource(props);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static DataSource getDataSource() {
return dataSource;
}
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
}