C3P0连接MySQL有两种方式
第一种: 相关参数 在程序中指定user url password
@Test
public void testc3p0_01() throws Exception {
//1.创建一个数据源对象
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
//2.通过配置文件mysql.properties
Properties properties = new Properties();
properties.load(new FileInputStream("src\\mysql.properties"));
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String url = properties.getProperty("url");
String driver = properties.getProperty("driver");
//给数据源comboPooledDataSource设置相关的参数
//连接的管理是由comboPooledDataSource管理的
comboPooledDataSource.setDriverClass(driver);
comboPooledDataSource.setJdbcUrl(url);
comboPooledDataSource.setUser(user);
comboPooledDataSource.setPassword(password);
//连接数初始化
comboPooledDataSource.setInitialPoolSize(10);
//最大连接数
comboPooledDataSource.setMaxPoolSize(50);
Connection connection = comboPooledDataSource.getConnection();//这个方法就是从DataSource接口实现的
System.out.println("连接成功");
}
第二种方式
public void testc3p0_02() throws SQLException {
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource("hsp_edu");
Connection connection = comboPooledDataSource.getConnection();
System.out.println("连接成功");
connection.close();
}
配置文件c3p0-config.xml 要区别于老的版本
<!--驱动-->
<property name="driverClass">com.mysql.cj.jdbc.Driver</property>
<!-- url-->
<property name="jdbcUrl">jdbc:mysql://localhost:3306/db02?useSSL=false&serverTimezone=UTC&characterEncoding=utf-8&autoReconnect=true</property>