DBCP
1、添加jar包
mysql-connector-java-5.1.7-bin.jar
commons-dbcp-1.4.jar
commons-pool.jar
2、添加配置文件
建议文件名为:dbcpconfig.properties
#<!-- 连接设置 -->
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mydb
username=root
password=root
#<!-- 初始化连接 -->
initialSize=10
#<!-- 最大连接数量 -->
maxActive=50
#<!-- 最大空闲连接 -->
maxIdle=20
#<!-- 最小空闲连接 -->
minIdle=5
#<!-- 超时等待时间(单位毫秒) -->
maxWait=50000
#<!-- 编码方式 -->
connectionProperties=useUnicode=true;characterEncoding=utf8
##<!-- 指定由连接池所创建的连接自动提交 -->
defaultAutoCommit=true
#<!-- 指定由连接池所创建的连接的事务级别 -->
defaultTransactionIsolation=REPEATABLE_READ
3、编写操作DBCP的工具类DBCPUtil
package com.etime;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;
public class DBCPUtil {
private static DataSource dataSource = null;
//创建数据库连接池
static {
Properties properties = new Properties();
try {
ClassLoader classLoader = DBCPUtil.class.getClassLoader();
InputStream inStream = classLoader.getResourceAsStream("dbcpconfig.properties");
properties.load(inStream);
dataSource = BasicDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
System.out.println(e.toString());
}
}
//建立连接
public static Connection getConnection() {
try {
return dataSource.getConnection();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
//释放连接
public static void release(Connection connection,Statement statement,ResultSet resultSet) {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (statement != null) {
try {
statement .close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
4、使用DBCP
public static void main(String[] args) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = DBCPUtil.getConnection();
String sql = "select * from student";
preparedStatement = connection.prepareStatement(sql);
resultSet = preparedStatement.executeQuery();
while(resultSet.next()) {
int studentID = resultSet.getInt("studentid");
String studentName = resultSet.getString("studentname");
Student student = new Student(studentID, studentName);
System.out.println(student);
}
} catch (Exception e) {
System.out.println(e.toString());
}finally {
DBCPUtil.release(connection, preparedStatement, resultSet);
}
}