1、导入jar包
c3p0-0.9.5.2.jar
mchange-commons-java-0.2.11.jar
2、源码:
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 <!--创建service对象,注入dao对象--> 19 <bean id="userSerivce" class="helloworld.c3p0.UserSerivce"> 20 <property name="userDao" ref="userDao"></property> 21 </bean> 22 23 <!--创建DAO对象,注入JdbcTemplate对象--> 24 <bean id="userDao" class="helloworld.c3p0.UserDao"> 25 <property name="jdbcTemplate" ref="jdbcTemplate"></property> 26 </bean> 27 28 <!--创建JdbcTemplate对象,注入连接池dataSource--> 29 <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> 30 <property name="dataSource" ref="dataSource"></property> 31 </bean> 32 33 </beans>
UserSerivce.java
1 package helloworld.c3p0; 2 3 public class UserSerivce { 4 private UserDao userDao; 5 6 public void setUserDao(UserDao userDao) { 7 this.userDao = userDao; 8 } 9 10 public void add(){ 11 userDao.add(); 12 } 13 }
UserDao.java
1 package helloworld.c3p0; 2 3 import org.springframework.jdbc.core.JdbcTemplate; 4 5 public class UserDao { 6 7 private JdbcTemplate jdbcTemplate; 8 9 public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { 10 this.jdbcTemplate = jdbcTemplate; 11 } 12 13 // 实现添加操作 14 public void add(){ 15 // 调用jdbcTemplate对象中的方法实现操作 16 String sql = "insert into user value(?,?,?)"; 17 // 表结构:id(int、自增),name(varchar 100),age(int 10) 18 int rows = jdbcTemplate.update(sql, null, "Tom3", 35); 19 System.out.println("插入行数:" + rows); 20 } 21 }
TestC3p0.java
1 package helloworld.c3p0; 2 3 import org.springframework.context.ApplicationContext; 4 import org.springframework.context.support.ClassPathXmlApplicationContext; 5 6 public class TestC3p0 { 7 public static void main(String[] args) { 8 ApplicationContext context = 9 new ClassPathXmlApplicationContext("beans_c3p0.xml"); 10 UserSerivce userSerivce = (UserSerivce) context.getBean("userSerivce"); 11 userSerivce.add(); 12 } 13 }