Spring之c3p0连接池配置和使用

时间:2023-03-08 20:54:41

1、导入包:c3p0和mchange包

2、代码实现方式:

 package helloworld.pools;

 import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import java.beans.PropertyVetoException; /**
* c3p0连接池使用方法-代码
* 导入包:c3p0和mchange包
*/
public class C3p0CodeImpl {
public static void main(String[] args) {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
try {
dataSource.setDriverClass("com.mysql.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql://10.15.1.200:3306/gxrdb");
dataSource.setUser("root");
dataSource.setPassword("root");
} catch (PropertyVetoException e) {
e.printStackTrace();
} // 设置数据源
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); // 调用jdbcTemplate对象中的方法实现操作
String sql = "insert into user value(?,?,?)";
//表结构:id(int、自增),name(varchar 100),age(int 10)
int rows = jdbcTemplate.update(sql, null, "Tom2", 25);
System.out.println("插入行数:" + rows);
}
}

3、Spring配置实现方式

beans.xml

 <beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:contexnt="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd"> <!--配置c3p0连接池-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!--注入属性-->
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://10.15.1.200:3306/gxrdb"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
</bean> </beans>