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
添加maven
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.1.1</version>
</dependency>
代码展示
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();
}
}
}
原文地址:https://www.cnblogs.com/feiqiangsheng/p/11406470.html
时间: 2024-11-05 12:25:15