一、DBCP 连接:
DBCP 连接池是 Apache 软件基金组织下的一个开源连接池实现。
需要的 java 包
commons - dbcp - 1.2.1.jar //连接池的实现
commons - pool - 1.2.jar //连接池实现的依赖库
commons - collection.jar //连接池实现的依赖库
主要代码:
import org.apache.commons.dbcp.BasicDataSource;
// 数据库池
private static BasicDataSource dataSource = new BasicDataSource();
public static Connection getConn(){
Connection con = null ;
try {
} catch (Exception e) {
}
return con ;
}
二、C3PO 连接:
C3PO 连接池是一个优秀的连接池,推荐使用。
需要的 java 包
c3po0.902.jar
主要代码:
import com.mchange.v2.c3p0.ComboPooledDataSource;
// 数据库池
private static ComboPooledDataSource dataSource = new ComboPooledDataSource();
public static Connection getConn(){
Connection con = null ;
try {
} catch (Exception e) {
}
return con ;
}
三、JndI与 Tomact 连接池
此连接池不需要其他的 java 包
1、在 Tomact 的 conf 文件下的 context.xml 中加上如下:
<Resource name="jdbc/mysql"
说明:
type: 指数据源类型;
name: 为这个Resource 的名字 "jdbc/mysql" 它与 下一步 在 web.xml 的文件中;
********************** 中的 “ jdbc/mysql ” 名字可以任意取
********************** 一定要一样,有三个地方要用 :context.xml, web.xml, java 程序中的类中,
maxActive: 表示 dbcp 的最大连接数目,0 为不受限制;
maxIdle: 表示 dbcp 空闲时的数据库连接的最大数目;
maxWait: 表示 dbcp 中的数据库接处于空闲状态的最长时间,0 为不受制。
username: 数据库用户名;
password: 数据库登录密码;
driverClassName: 指数据库的 jdbc 驱动程序
url :中有个 test 它是 mysql 中的一个数据库的名字
2、web.xml configuration
<resource-ref>
</resource-ref>
3、测试:
在 mysql 数据库中有个 test 数据库
test 中有表如下
html 测试:
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<body>
</body>
java 程序测试:
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public Connection getConn() {
Connection conn = null ;
try {
} catch (SQLException e) {
} catch (NamingException e) {
}
return conn;
}