Spring之c3p0连接池配置和使用

1、导入包:c3p0和mchange包

2、代码实现方式:

 1 package helloworld.pools;
 2 
 3 import com.mchange.v2.c3p0.ComboPooledDataSource;
 4 import org.springframework.jdbc.core.JdbcTemplate;
 5 import java.beans.PropertyVetoException;
 6 
 7 /**
 8  * c3p0连接池使用方法-代码
 9  * 导入包:c3p0和mchange包
10  */
11 public class C3p0CodeImpl {
12     public static void main(String[] args) {
13         ComboPooledDataSource dataSource = new ComboPooledDataSource();
14         try {
15             dataSource.setDriverClass("com.mysql.jdbc.Driver");
16             dataSource.setJdbcUrl("jdbc:mysql://10.15.1.200:3306/gxrdb");
17             dataSource.setUser("root");
18             dataSource.setPassword("root");
19         } catch (PropertyVetoException e) {
20             e.printStackTrace();
21         }
22 
23         // 设置数据源
24         JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
25 
26 //        调用jdbcTemplate对象中的方法实现操作
27         String sql = "insert into user value(?,?,?)";
28         //表结构:id(int、自增),name(varchar 100),age(int 10)
29         int rows = jdbcTemplate.update(sql, null, "Tom2", 25);
30         System.out.println("插入行数:" + rows);
31     }
32 }

3、Spring配置实现方式

beans.xml

 1 <beans xmlns="http://www.springframework.org/schema/beans"
 2        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3        xmlns:contexnt="http://www.springframework.org/schema/context"
 4        xsi:schemaLocation="http://www.springframework.org/schema/beans
 5         http://www.springframework.org/schema/beans/spring-beans.xsd
 6         http://www.springframework.org/schema/context
 7         http://www.springframework.org/schema/context/spring-context-2.5.xsd">
 8 
 9     <!--配置c3p0连接池-->
10     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
11         <!--注入属性-->
12         <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
13         <property name="jdbcUrl" value="jdbc:mysql://10.15.1.200:3306/gxrdb"></property>
14         <property name="user" value="root"></property>
15         <property name="password" value="root"></property>
16     </bean>
17 
18 
19 </beans>

 

posted @ 2017-12-19 12:56  星瑞  阅读(1233)  评论(0编辑  收藏  举报