赞
踩
web项目-->WebRoot-->WEB-INF导入C3P0的jar包(c3p0-0.9.1.2.jar)、数据库驱动jar包(ojdbc14.jar)
web项目-->src-->新建c3p0.properties文件并进行配置:
#数据库信息相关参数
c3p0.driverName=oracle.jdbc.driver.OracleDriver
c3p0.url=jdbc:oracle:thin:@localhost:1521:XE
c3p0.userName=
c3p0.pwd=
#连接池相关参数
c3p0.minPoolSize=10
c3p0.maxPoolSize=100
c3p0.maxIdleTime=60
c3p0.initialPoolSize=10
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{
Map<String,String> kvs = PropertiesUtil.getKvs("c3p0.properties");
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 main(String[] args) {
System.out.println(getConnection());
}
}
web项目-->src-->com.niit.util-->PropertiesUtil.java
package com.niit.util;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.Map.Entry;
public class PropertiesUtil {
private PropertiesUtil(){}
public static Map<String,String> getKvs(String path){
Properties prop = new Properties();
Map<String,String> map = new HashMap<String, String>();
try{
prop.load(PropertiesUtil.class.getClassLoader().getResourceAsStream(path));
Set<Entry<Object,Object>> set = prop.entrySet();
for(Entry<Object,Object> e : set){
map.put(String.valueOf(e.getKey()), String.valueOf(e.getValue()));
}
}catch(IOException e){
System.out.println("读取配置文件失败!");
// e.printStackTrace();
}
return map;
}
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();
}
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。