C3P0是什么
C3P0是一个开源的JDBC连接池,它实现了数据源和JNDI绑定,支持JDBC3规范和JDBC2的标准扩展。目前使用它的开源项目有Hibernate、Spring等。
1.基础连接方式
第一步 创建一个ComboPooledDataSource对象
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
第二步 配置加载连接数据库信息
//加载MySQL驱动
comboPooledDataSource.setDriverClass("com.mysql.jdbc.Driver");
//建立连接 jdbc:mysql://localhost:3306/student
// 使用的技术:数据库名称://地址:端口号/数据库名
comboPooledDataSource.setJdbcUrl("jdbc:mysql://localhost:3306/student");
//数据库用户名
comboPooledDataSource.setUser("root");
//数据库密码
comboPooledDataSource.setPassword("root");
第三步 获取connection
Connection connection = comboPooledDataSource.getConnection();
2.配置文件加载连接数据库
第一步 在maven配置文件中的dependencies标签中添加jar包或者直接把.jar文件放在项目中
<!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
<!--c3p0-->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
第二部 创建一个c3p0-config.xml的c3p0配置文件 并在文件中添加如下内容
<c3p0-config>
<!-- This app is massive! -->
<named-config name="helloc3p0">//命名配置
//配置加载驱动
<property name="driverClass">com.mysql.jdbc.Driver</property>
//配置建立连接数据库
<property name="jdbcUrl">jdbc:mysql://localhost:3306/student</property>
//配置数据库用户名
<property name="user">root</property>
//配置数据库密码
<property name="password">root</property>
</named-config>
</c3p0-config>
第三步 获取外部配置文件和connection
//1.获取外部配置文件
ComboPooledDataSource helloc3p0 = new ComboPooledDataSource("helloc3p0");//获取配置名为helloc3p0的配置信息
//2.获取connection
Connection connection = helloc3p0.getConnection();
在实际的开发中通常使用配置文件加载连接数据库