整理的dbpc工具类

为了方便使用特地对dbpc写了个帮助类,特记录于此:

package db.dbpc;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.Statement;
import java.util.Properties;

/**
 *  dbpc数据库连接池
 *  参数说明:   
 *  driveClassName:JDBC驱动类的完整的名称;
 *  maxActive:同时能够从连接池中被分配的可用实例的最大数;
 *  maxIdle:可以同时闲置在连接池中的连接的最大数;
 *  maxWait:最大超时时间,以毫秒计;
 *  password:用户密码;
 *  url:到JDBC的URL连接;
 *  user:用户名称;
 *  validationQuery:用来查询池中空闲的连接;
 *  initialSize 初始连接池连接个数;  
 * @author dxz
 *
 */
public class DBHelp {
	private static BasicDataSource dataSource = null;
	private static String username = "webcj";
	private static String password = "webcj";
	private static String url = "jdbc:mysql://localhost:3306/webcj";
	private static String drive = "com.mysql.jdbc.Driver";
	private static String maxActive = "30";
	private static String maxIdle = "10";
	private static String maxWait = "10000";
	private static String removeAbandoned = "false";
	private static String removeAbandonedTimeout = "120";
	private static String testOnBorrow = "true";
	private static String logAbandoned = "true";
	

    public static void init() throws Exception {

        if (dataSource != null) {
            dataSource.close();
            dataSource = null;
        }

    
            Properties p = new Properties();
            p.setProperty("driverClassName", drive);
            p.setProperty("url", url);
            p.setProperty("password", password);
            p.setProperty("username", username);
            p.setProperty("maxActive", maxActive);
            p.setProperty("maxIdle", maxIdle);
            p.setProperty("maxWait", maxWait);
            p.setProperty("removeAbandoned", removeAbandoned);
            p.setProperty("removeAbandonedTimeout", removeAbandonedTimeout);
            p.setProperty("testOnBorrow", testOnBorrow);
            p.setProperty("logAbandoned", logAbandoned);

            dataSource = (BasicDataSource) BasicDataSourceFactory.createDataSource(p);

      
    }


    public static synchronized Connection getConnection() throws  Exception {
        if (dataSource == null) {
            init();
        }
        Connection conn = null;
        if (dataSource != null) {
            conn = dataSource.getConnection();
        }
        return conn;
    }
	
}

 

 

你可能感兴趣的:(java,apache,sql,mysql,jdbc)