Druid连接池
目标
能够掌握Druid连接池的使用
讲解
Druid是阿里巴巴开发的号称为监控而生的数据库连接池,Druid是目前最好的数据库连接池。在功能、性能、扩展性方面,都超过其他数据库连接池,同时加入了日志监控,可以很好的监控数据库连接池和SQL的执行情况。Druid已经在阿里巴巴部署了超过600个应用,经过一年多生产环境大规模部署的严苛考验。
Druid地址:https://github.com/alibaba/druid
DRUID连接池使用的jar包:druid-1.0.9.jar
Druid常用的配置参数
Druid连接池基本使用
API介绍
com.alibaba.druid.pool.DruidDataSourceFactory类有创建连接池的方法
public static DataSource createDataSource(Properties properties)
创建一个连接池,连接池的参数使用properties中的数据复制
我们可以看到Druid连接池在创建的时候需要一个Properties对象来设置参数,所以我们使用properties文件来保存对应的参数。
Druid连接池的配置文件名称随便,放到src目录下面方便加载
druid.properties文件内容:
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/day17
username=root
password=root
initialSize=5
maxActive=10
maxWait=3000复制
使用步骤
导入druid的jar包
在src目录下创建一个properties文件,并设置对应参数
加载properties文件的内容到Properties对象中
创建Druid连接池,使用配置文件中的参数
从Druid连接池中取出连接
执行SQL语句
关闭资源
案例代码
在src目录下新建一个Druid配置文件,命名为:druid.properties,内容如下
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/day25
username=root
password=root
initialSize=5
maxActive=10
maxWait=3000复制
java代码
public class Demo04 {
public static void main(String[] args) throws Exception {
// 加载配置文件中的配置参数
InputStream is = Demo04.class.getResourceAsStream("/druid.properties");
Properties pp = new Properties();
pp.load(is);
// 创建连接池,使用配置文件中的参数
DataSource ds = DruidDataSourceFactory.createDataSource(pp);
//for (int i = 0; i < 10; i++) {
//Connection conn = ds.getConnection();
//System.out.println(conn);
//}
// 从连接池中取出连接
Connection conn = ds.getConnection();
// 执行SQL语句
String sql = "INSERT INTO student VALUES (NULL, ?, ?, ?);";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, "王五");
pstmt.setInt(2, 35);
pstmt.setDouble(3, 88.5);
int i = pstmt.executeUpdate();
System.out.println("影响的行数:" + i);
// 执行查询
sql = "SELECT * FROM student;";
ResultSet rs = pstmt.executeQuery(sql);
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
double score = rs.getDouble("score");
System.out.println("id: " + id + " ,name: " + name + " ,age = " + age + " ,score = " + score);
}
pstmt.close();
conn.close(); // 将连接还回连接池中
}
}复制
案例效果
1. 正常获取连接池中的连接
2. 取连接池中的连接超时
3. 使用DRUID连接池中的连接操作数据库
小结
Druid使用步骤?
1.导入jar包:druid-1.0.9.jar
2.复制配置文件到src下:druid.properties,修改参数
3.创建Properties对象,加载druid.properties中的内容
4.创建连接池: DruidDataSourceFactory.createDataSource(Properties pp)5.获取连接6.后续使用
Druid常用的配置参数
Druid连接池基本使用不管是C3P0连接池,配置大致都可以分为2种:
1.连接数据库的参数,
2.连接池的参数,这2种配置大致参数作用都相同,只是参数名称可能不一样。