package com.jb.jubmis.comm;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.apache.commons.dbcp.BasicDataSource;
/**
* 使用abcp连接池
* @author admin
*所需JAR包:commons-pool-1.6.jar、commons-collections-3.2.1.jar、commons-dbcp-1.4.jar
*
*/
public class DBCPDataSourceUtils {
// private static final String DRIVER_NAME = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
private static final int INITIAL = 50;//初始化50个连接
private static final int MAX_ACTIVE = 500;//最大值500个连接
private static final int MAX_IDLE = 10;//最大空闲10
private static final long MAX_WAIT = 2 * 1000;//超过500个访问,等待的时间
private static final String DRIVER_NAME = "org.sqlite.JDBC";//数据库jar驱动,我这里是使用的的sqlite测试
private static BasicDataSource bds;
static{
if(bds == null){
bds = new BasicDataSource();
}
bds.setDriverClassName(DRIVER_NAME);
bds.setInitialSize(INITIAL);
bds.setMaxActive(MAX_ACTIVE);
bds.setMaxIdle(MAX_IDLE);
bds.setMaxWait(MAX_WAIT);
}
/**
* 打开连接池
* @param path 数据库的路径
* @return
* @throws SQLException
*/
public static Connection getSqliteConnection(String path) throws SQLException{
bds.setUrl("jdbc:sqlite:" + path);//数据库的路径, 我这里是使用的的sqlite测试
//bds.setUsername("");//数据库用户
//bds.setPassword("");//数据库密码
return bds.getConnection();
}
/**
* 释放数据库连接
*
* @param rs
* @param st
* @param conn
*/
public static void freeConnection(ResultSet rs, Statement st,
Connection conn) {
try {
if (rs != null)
rs.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (st != null)
st.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (conn != null)
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
=============一些jdbc连接的方式经过和上面连接池比较发现连接池效率非常高=================
public Connection connOpen() throws SQLException {
Connection conn =null;
try {
Class.forName("org.sqlite.JDBC");
conn =DriverManager.getConnection("jdbc:sqlite:" + path);
} catch(ClassNotFoundException e) {
e.printStackTrace();
}
return conn;
}