-
Druid是阿里巴巴开源连接池组件,是最好的连接池之一
-
Druid对数据库连接进行有效管理与重用,最大化程序执行效率
-
连接池负责创建管理连接程序只负责取用与归还
Druid连接池的配置与使用
引入依赖
com.alibaba druid1.1.12
创建属性文件
druid-config.properties
# 配置数据库的连接参数 driverClassName= com.mysql.cj.jdbc.Driver url=jdbc:mysql://localhost:3306/servicecenter?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=true username=root password=root # 配置连接池的参数 initialSize=5 //连接池准备好之后会默认地创建5个数据库连接 maxActive=10 //若5个链接不够用,那么由连接池创建新的连接,但是总数不超过10 maxWait=3000 maxIdle=6 minIdle=3
创建类
DruidSample
public class DruidSample {
public static void main(String[] args) {
//1.加载属性文件
Properties properties = new Properties();
String propertyFile = DruidSample.class.getResource("druid-config.properties").getPath();
//路径中 空格->%20 C: java codedruid-config.properties
//c:java%20codedruid-config.properties
try {
propertyFile = new URLDecoder().decode(propertyFile,"UTF-8");
} catch (UnsupportedEncodingException e) { //捕捉不支持的编码异常
e.printStackTrace();
}
try {
properties.load(new FileInputStream(propertyFile));
} catch (Exception e) {
e.printStackTrace();
}
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
//2.获取DataSource数据源对象
DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
//3.创建数据库连接
conn = dataSource.getConnection();
pstmt = conn.prepareStatement("selete * from employee limit 0,10");
rs = pstmt.executeQuery();
while (rs.next()) {
Integer empId = rs.getInt(1) ;
String ename = rs.getString ("ename") ;
String dname = rs.getString ("dname") ;
Float salary = rs.getFloat ("salary") ;
System.out.println(dname + "-" + empId + "-" + ename + "-" + salary);
} catch (Exception e) {
e.printStackTrace();
}finally {
DbUtils.closeConnection(rs,pstmt,conn);
}
}
}
C3P0连接池
c3p0-config.xml
com.mysql.cj.jdbc.Driver jdbc:mysql://localhost:3306/servicecenter?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=true root root 10 20
C3P0Sample
public class C3P0Sample {
public static void main(String[] args) {
//1.加载属性文件
//2.获取DataSource数据源对象
DataSource dataSource = ComboPooledDataSource();
//3.创建数据库连接
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try{
conn = dataSource.getConnection();
pstmt = conn.prepareStatement("selete * from employee limit 0,10");
rs = pstmt.executeQuery();
while (rs.next()) {
Integer empId = rs.getInt(1) ;
String ename = rs.getString ("ename") ;
String dname = rs.getString ("dname") ;
Float salary = rs.getFloat ("salary") ;
System.out.println(dname + "-" + empId + "-" + ename + "-" + salary);
} catch (Exception e) {
e.printStackTrace();
}finally {
DbUtils.closeConnection(rs,pstmt,conn);
}
}
}
暑期编程PK赛
得CSDN机械键盘等精美礼品!


