传统连接的弊端
1 传统的JDBC连接使用DriverManager来获取,每次向数据库建立连接的时候都要将Connection 加载到内存,验证ip 密码 等数据, 占用资源较多.
2 每一次连接都需要关闭,但如果出现异常,可能会忽略关闭操作,导致内存泄露.
3 传统的连接方式还会因为连接数量过多而崩溃
引出数据库连接池技术
c3p0方法
无(暂时没找到jar)
德鲁伊方法
1导入德鲁伊jar
2配置xml文件
连接前需设置好xml配置文件参数
#key=value
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/fzhl_?rewriteBatchedStatements=true
username=root
password=root
#初始化的连接数
initialSize=10
#最小连接数
minIdle=5
#最大连接数
maxActive=50
#最大等待时间
maxWait=5000
开始应用(代码展示)
public class Main1 {
public static void main(String[] args) throws Exception{
Properties properties = new Properties();
properties.load(new FileInputStream("src\\druid.properties"));
//创建数据库连接池 读取设置的xml配置文件后初始化
DataSource dataSource = DruidDataSourceFactory.createDataSource((properties));
// 获取连接操作
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
long t1 = System.currentTimeMillis();
// 多次连接演示
for (int i=0;i<500;i++){
Connection connection1 = dataSource.getConnection();
connection1.close();
}
System.out.println(System.currentTimeMillis()-t1);
}
}
工具封装的使用
public class Main2 {
// 编写德鲁伊工具类
// 在静态代码块完成 ds 初始化
private static DataSource dataSource;
static {
Properties properties = new Properties();
try {
properties.load(new FileInputStream("src\\druid.properties"));
dataSource = DruidDataSourceFactory.createDataSource(properties);
}catch (Exception e){
e.printStackTrace();
}
}
// 获取连接
public static Connection getconnection() {
try {
return dataSource.getConnection();
}catch (Exception e){
e.printStackTrace();
return null;
}
}
// 关闭流
public static void closeconnection(Connection connection){
try {
if(connection!=null){
connection.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
public static void closeconnection(ResultSet resultSet,Connection connection){
try {
if(resultSet!=null){
resultSet.close();
}
closeconnection(connection);
}catch (Exception e){
e.printStackTrace();
}
}
public static void closeconnection(ResultSet resultSet, Statement statement,Connection connection){
try {
closeconnection(resultSet,connection);
if(statement!=null){
statement.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
public static void closeconnection(ResultSet resultSet, PreparedStatement statement,Connection connection){
try {
closeconnection(resultSet,connection);
if(statement!=null){
statement.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
}
调用工具类
public class Main3 {
public static void main(String[] args) throws Exception{
Connection connection = Main2.getconnection();
String sql = "select * from fz03";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
ResultSet resultSet = preparedStatement.executeQuery(sql);
while (resultSet.next()){
System.out.println(resultSet.getInt(1)+" "+resultSet.getString(2)+" "+resultSet.getInt(3)+" "+resultSet.getNString(4));
}
Main2.closeconnection(resultSet,preparedStatement,connection);
}
}