需要commons-collections,commons-dbcp,commons-pool
dbcpconfig.properties
#连接设置
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
username=root
password=root
#<!-- 初始化连接 -->
initialSize=10
#最大连接数量
maxActive=50
#<!-- 最大空闲连接 -->
maxIdle=20
#<!-- 最小空闲连接 -->
minIdle=5
#<!-- 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒 -->
maxWait=60000
#JDBC驱动建立连接时附带的连接属性属性的格式必须为这样:[属性名=property;]
#注意:"user" 与 "password" 两个属性会被明确地传递,因此这里不需要包含他们。
connectionProperties=useUnicode=true;characterEncoding=gbk
#指定由连接池所创建的连接的自动提交(auto-commit)状态。
defaultAutoCommit=true
#driver default 指定由连接池所创建的连接的只读(read-only)状态。
#如果没有设置该值,则“setReadOnly”方法将不被调用。(某些驱动并不支持只读模式,如:Informix)
defaultReadOnly=
#driver default 指定由连接池所创建的连接的事务级别(TransactionIsolation)。
#可用值为下列之一:(详情可见javadoc。)NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE
defaultTransactionIsolation=READ_COMMITTED
JdbcUtils
public final class JdbcUtils {
private static DataSource dataSource;
static {
try {
Properties properties = new Properties();
InputStream is = JdbcUtils.class.getClassLoader()
.getResourceAsStream("dbcpconfig.properties");
properties.load(is);
dataSource = BasicDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
throw new ExceptionInInitializerError(e);
}
}
private JdbcUtils() {
}
public static Connection getConnection() throws SQLException {
// return DriverManager.getConnection(url, user, password);
return dataSource.getConnection();
}
public static void realse(ResultSet rs, Statement st, Connection conn)
throws SQLException {
try {
if (rs != null)
rs.close();
} finally {
try {
if (st != null)
st.close();
} finally {
if (conn != null)
conn.close();
}
}
}
}