DBCP介绍
DBCP是Java开源连接池中常用的一种,它一般应用在使用数据库频繁的系统中,可以处理大量数据库连接请求。
简单配置
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/test
username=root
password=123456
maxActive=50
maxIdle=20
maxWait=60000
添加依赖
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.1.1</version>
</dependency>
代码展示
DBUtil工具类
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp2.BasicDataSourceFactory;
public class DBUtil {
private static DataSource ds;
private static Connection conn;
static {
try {
Properties properties = new Properties();
InputStream inStream = DBUtil.class.getResourceAsStream("dataSouce.properties");
properties.load(inStream);
ds = BasicDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
// 获取连接
public static Connection getConn() throws SQLException {
if (conn == null || conn.isClosed()) {
conn = ds.getConnection();
}
return conn;
}
// 回收连接
public static void closeConn() {
try {
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
conn = null;
}
}
}
操作数据库
import java.sql.Connection;
import java.sql.Statement;
public class Test {
public static void main(String[] args) throws Exception {
Connection conn = DBUtil.getConn();
conn.setAutoCommit(false);
Statement stmt = conn.createStatement();
int rs = stmt.executeUpdate("DELETE FROM user WHERE name='qiang'");
if (rs > 0) {
System.out.println("更新成功!");
conn.rollback();
} else {
System.out.println("更新失败!");
conn.commit();
} finally {
stmt.close();
DBUtil.closeConn();
}
}
}