web项目-->WebRoot-->WEB-INF导入C3P0的jar包(c3p0-0.9.1.2.jar)、数据库驱动jar包(ojdbc14.jar)
web项目-->src-->c3p0-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<!-- 如果代码中的config名称不是下面的某一个,就会根据默认配置进行查找,如果也没有默认配置,则按照默认值配置进行查找 -->
<default-config>
<property name="jdbcUrl">jdbc:oracle:thin://@localhost:1521:XE</property>
<property name="driverClass">oracle.jdbc.driver.OracleDriver</property>
<property name="user">scott</property>
<property name="password">smq</property>
<property name="checkoutTimeout">30000</property>
<property name="initialPoolSize">10</property>
<property name="maxIdleTime">60</property>
<property name="maxPoolSize">100</property>
<property name="minPoolSize">10</property>
</default-config>
<!-- 配置生产环境的数据库 -->
<named-config name="oracle_pro">
<property name="jdbcUrl">jdbc:oracle:thin://@localhost:1521:XE</property>
<property name="driverClass">oracle.jdbc.driver.OracleDriver</property>
<property name="user">scott</property>
<property name="password">smq</property>
<property name="checkoutTimeout">30000</property>
<property name="initialPoolSize">10</property>
<property name="maxIdleTime">30</property>
<property name="maxPoolSize">100</property>
<property name="minPoolSize">10</property>
</named-config>
<!-- 配置开发环境的数据库 -->
<named-config name="oracle_dev">
<property name="jdbcUrl">jdbc:oracle:thin://@localhost:1521:XE</property>
<property name="driverClass">oracle.jdbc.driver.OracleDriver</property>
<property name="user">scott</property>
<property name="password">smq</property>
<property name="checkoutTimeout">30000</property>
<property name="initialPoolSize">10</property>
<property name="maxIdleTime">30</property>
<property name="maxPoolSize">100</property>
<property name="minPoolSize">10</property>
</named-config>
</c3p0-config>
web项目-->src-->com.niit.util-->DBUtil.Java
package com.niit.util;
import java.beans.PropertyVetoException;
import java.util.Map;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class DBUtil {
private static ComboPooledDataSource ds = null;
private DBUtil(){}
static{
//2、xml文件方式:
ds = new ComboPooledDataSource("oracle");
}
public synchronized static Connection getConnection(){
Connection con = null;
try {
con = ds.getConnection();
} catch (SQLException e) {
System.out.println("获取数据库连接失败!");
// e.printStackTrace();
}
return con;
}
public synchronized static Connection getConnection(){
Connection con = null;
try {
con = ds.getConnection();
} catch (SQLException e) {
System.out.println("获取数据库连接失败!");
// e.printStackTrace();
}
return con;
}
public static void closeResource(ResultSet rs,Statement stmt,Connection con){
try {
if(rs != null){
rs.close();
}
if(stmt != null){
stmt.close();
}
if(con != null){
con.close();
}
}catch (SQLException e) {
System.out.println("关闭资源失败!");
// e.printStackTrace();
}
}
public static void main(String[] args) {
System.out.println(getConnection());
}
}