- 在没有数据库连接池情况下频繁的建立 / 释放连接对数据库来说增加了系统负担,应用程序每次操作数据库的过程将会变得很慢;应用系统每次建立连接都要占用一个端口,频繁的建立/释放,每个被释放的连接在发出释放请求之后并不是马上就执行,必须经历一个 FIN 阶段的等待直到确认为止。所以在每秒几千次数据库请求的时候,应用服务器端口很有可能被消耗完。
- 数据库连接池是一个容器,负责分配、管理数据库连接,允许应用程序重复使用一的现有的数据库连接,而不是频繁建立新的数据库连接
- 可以通过设置最大空闲时间来避免由于没有释放数据库连接引起的数据库连接遗漏
- 使用数据库连接池提高了连接资源的重用、系统响应速度
代码示例:
package com.polarbear.demo;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;
/**
* 1. 获取Connection:Connection connection = dataSource.getConnection();
* 2. 定义SQL:String sql = "select * from admin where name = ? and password = ?";
* 3. 获取PreparedStatement对象:PreparedStatement statement = connection.prepareStatement(sql);
* 4.设置参数:statement.setString(1, loginName);statement.setString(2, loginPass);
* 5.执行SQL:ResultSet resultSet = statement.executeQuery();
* 6.处理结果:if (resultSet.next()){
* System.out.println("登陆成功!");
* } else {
* System.out.println("登录失败!");
* }
* 7.释放资源:connection.close();statement.close();
*/
public class druid {
public static void main(String[] args){
String loginName = "admin";
String loginPass = "1230";
String sql = "select * from admin where name = ? and password = ?";
Properties properties = new Properties();
try{
FileInputStream fileInputStream = new FileInputStream("src/druid.properties");
properties.load(fileInputStream);
DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
Connection connection = dataSource.getConnection();
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, loginName);
statement.setString(2, loginPass);
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()){
System.out.println("登陆成功!");
} else {
System.out.println("登录失败!");
}
System.out.println(connection);
System.out.println(System.getProperty("user.dir"));
connection.close();
statement.close();
} catch (Exception e) {
System.out.println("加载配置文件失败或连接数据源失败");
e.printStackTrace();
}
}
}
配置文件:
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/tp_music?serverTimezone=Asia/Shanghai&useSSL=false&useServerPrepStmts=true
username=root
password=1026
# 初始化连接数量
initialSize=5
# 最大化连接数
maxActive=10
# 最大等待时间
maxWait=3000