1. 程式人生 > >Spring之c3p0連接池配置和使用

Spring之c3p0連接池配置和使用

實現 style 操作 except text org mbo c3p0連接池 pda

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>

Spring之c3p0連接池配置和使用