当前位置:   article > 正文

Web项目配置数据源——c3p0_properties_c3p0properties

c3p0properties

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");
ds = new ComboPooledDataSource();
try {
ds.setDriverClass(kvs.get("c3p0.driverName"));
ds.setJdbcUrl(kvs.get("c3p0.url"));
ds.setUser(kvs.get("c3p0.userName"));
ds.setPassword(kvs.get("c3p0.pwd"));
ds.setMinPoolSize(Integer.parseInt(kvs.get("c3p0.minPoolSize")));
ds.setMaxPoolSize(Integer.parseInt(kvs.get("c3p0.maxPoolSize")));
ds.setMaxIdleTime(Integer.parseInt(kvs.get("c3p0.maxIdleTime")));
ds.setInitialPoolSize(Integer.parseInt(kvs.get("c3p0.initialPoolSize")));
} catch (PropertyVetoException e) {
System.out.println("配置数据源失败!");
// e.printStackTrace();
}

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();
}
}


}


本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号