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>
这篇博客介绍了使用C3P0连接MySQL数据库的两种方法。第一种方法是在程序中直接指定数据库连接的user、url、password和driver,然后设置连接池的相关参数。第二种方法则是通过配置文件c3p0-config.xml来配置数据源,简化了代码中的数据库连接信息。博客还提到了配置文件c3p0-config.xml的新格式,包括driverClass、jdbcUrl等属性的设置。
1504

被折叠的 条评论
为什么被折叠?



