JDBC和数据库连接池-两个工具类-JDBCUtilsByDruid和BasicDAO

JDBC和数据库连接池-两个工具类-JDBCUtilsByDruid和BasicDAO

这是一篇总结文章。

1、学习技术的梳理

1.1、jdbc的引入

在学习mysql交互这一块,一开始引入了JDBC接口的学习。引入的jar包为:mysql-connector-java-5.1.37-bin.jar.

jdbc的思路是:

  • 注册驱动
    Driver driver=new Driver();
  • 获取连接【这里有五种方式,推荐使用第五种方式,如下:
    String url="jdbc:mysql://localhost:3306/hsp_db02";
    Properties properties = new Properties();
    //说明 user 和 password 是规定好,后面的值根据实际情况写
    properties.setProperty("user", "root");// 用户
    properties.setProperty("password", "123456"); //密码

    Connection connect=driver.connect(url,properties);
  • 发送sql指令,执行增删改查【Statement会被SQL注入,推荐使用PreparedStatement预处理
    String sql = "delete from actor where id = 1";
    //statement 用于执行静态 SQL 语句并返回其生成的结果的对象
    Statement statement = connect.createStatement();//这种方法容易被SQL注入
    int rows = statement.executeUpdate(sql); // 如果是 dml 语句,返回的就是影响行数
    System.out.println(rows > 0 ? "成功" : "失败");
  • 断开连接。
statement.close();
connect.close();

获取连接的第五种方式:就是把数据库的配置信息写到properties文件里,然后通过FileInpuStream流读取配置文件:

img

		Properties properties = new Properties();
        properties.load(new FileInputStream("src\\jdbc.properties"));//读取配置文件

        String url= properties.getProperty("url");
        String username= properties.getProperty("username");
        String password= properties.getProperty("password");

        Connection conn = DriverManager.getConnection(url, username, password);//通过DriverManager获取连接

1.2、ResultSet[结果集]

1.1jdbc引入中,展示的是插入、删除、修改的功能,因为这三种功能叫dml操作,dml操作返回的是受操作的行数,如果我们需要查询多行记录、表记录,那么就需要用到 ResultSet[结果集]

这里因此引入:ResultSet[结果集]

 @Test
    public void zuoye01() throws ClassNotFoundException, IOException, SQLException {
    
    
        Class.forName("com.mysql.jdbc.Driver");//可写可不写,自动注册驱动类

        //读取配置文件
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\jdbc.properties"));
        //获取连接
        String url= properties.getProperty("url");
        String username= properties.getProperty("username");
        String password = properties.getProperty("password");

        Connection coon = DriverManager.getConnection(url, username, password);//这里面已经完成了注册Driver驱动类了,所以第一句可写可不写

        //sql
        String sql="select * from news";

        PreparedStatement preparedStatement = coon.prepareStatement(sql);//这里不用statement了,使用PreparedStatement预处理**
        ResultSet resultSet = preparedStatement.executeQuery();//返回**ResultSet[结果集]**
       
        //【!】下面这个返回集操作太麻烦了,后面通过Apache公司的DBUtils工具进行封装,可以看目录
        while (resultSet.next()){
    
    
            int id = resultSet.getInt("id");
            String content = resultSet.getString("content");
            System.out.println(id+"\t"+content);
        }


        //关闭连接
       preparedStatement.close();
       coon.close();
    }

img

1.3API小结

在这里插入图片描述

2、数据库连接池

传统jdbc技术连接数据库有如下问题:

img

img

我们选择数据库连接池是 德鲁伊数据库连接池Druid,引入jar:druid-1.2.8.jar.

我们用这个德鲁伊数据库连接池的目的是:获取数据库连接connect,下面的基于Druid(德鲁伊)的 JDBCUtils 工具类就在解决这个问题。

private static DataSource ds;
//在静态代码块完成 ds 初始化
static {
    
    
Properties properties = new Properties();
try {
    
    
properties.load(new FileInputStream("src\\druid.properties"));
ds = DruidDataSourceFactory.createDataSource(properties);//通过工厂获取数据库连接池对象
} catch (Exception e) {
    
    
e.printStackTrace();
}
}
//编写 getConnection 方法
public static Connection getConnection() throws SQLException {
    
    
return ds.getConnection();
}


connection = JDBCUtilsByDruid.getConnection();//获取数据库连接的方法变简单了,效率高了。

3、Apache公司的DBUtils工具-BasicDAO【重要!】

这个工具在于解决封装ResultSet[结果集]封装jdbc,该工具是 DBUtils+数据库连接池(Druid)集合体

apache-DBUtils 工具类 + druid:

img

img

BasicDAO.java:

package com.linghu.dao;

import com.linghu.utils.JDBCUtilsByDruid;

import jdk.nashorn.internal.scripts.JD;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * @author 令狐荣豪
 * @version 1.0
 */
public class BasicDAO<T> {
    
    
    private QueryRunner qr=new QueryRunner();

    /**
     * 修改-表-记录的操作。
     * @param sql
     * @param parameters
     * @return
     */
    public int update(String sql,Object... parameters){
    
    
        Connection connection=null;

        try {
    
    
           connection= JDBCUtilsByDruid.getConnection();

            int update = qr.update(connection, sql, parameters);

            return update;

        } catch (SQLException e) {
    
    
            throw new RuntimeException(e);
        } finally {
    
    
            JDBCUtilsByDruid.close(null,null,connection);
        }
    }

    /**
     *查询多行多列的操作,返回多行
     * @param sql
     * @param clazz 传入一个类的Class对象,比如Actor.class[反射机制]
     * @param parameters
     * @return 根据Actor.class返回对应的ArrayList集合
     */
     public List<T> queryMulti(String sql,Class<T> clazz,Object... parameters){
    
    

       Connection connection=null;

         try {
    
    
             connection=JDBCUtilsByDruid.getConnection();
             return qr.query(connection,sql,new BeanListHandler<T>(clazz),parameters);
         } catch (SQLException e) {
    
    
             throw new RuntimeException(e);
         } finally {
    
    
             JDBCUtilsByDruid.close(null,null,connection);
         }

     }

    /**
     * 查询单行多列的操作,返回单行多列
     * @param sql
     * @param clazz
     * @param parameters
     * @return
     */
     public T querySingle(String sql,Class<T> clazz,Object...parameters){
    
    
         Connection connection=null;
         try {
    
    
             connection= JDBCUtilsByDruid.getConnection();
            return qr.query(connection,sql,new BeanHandler<T>(clazz),parameters);
         } catch (SQLException e) {
    
    
             throw new RuntimeException(e);
         } finally {
    
    
             JDBCUtilsByDruid.close(null,null,connection);
         }
     }

    /**
     * 查询单行单列,返回单行单列,返回单值的方法
     * @param sql
     * @param parameters
     * @return 返回单值
     */
     public Object queryScalar(String sql,Object... parameters){
    
    

         Connection connection=null;

         try {
    
    
             connection= JDBCUtilsByDruid.getConnection();
             Object query = qr.query(connection, sql, new ScalarHandler(), parameters);
             return query;
         } catch (SQLException e) {
    
    
             throw new RuntimeException(e);
         } finally {
    
    
             JDBCUtilsByDruid.close(null,null,connection);
         }
     }



}

4、基于Druid(德鲁伊)的 JDBCUtils 工具类- **JDBCUtilsByDruid【重要!】

这个工具类封装了jdbc中的建立连接释放连接。这个工具类可以让我们更方便获取连接对象connect.

img

druid.properties:

driverClassName=com.mysql.jdbc.Driver
#URL??????URL???travel????????????????????????????
url=jdbc:mysql://localhost:3306/mhl?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
characterEncoding=utf-8
#??mysql??????????
username=root
password=123456
#??????????
initialSize=5
#???????
maxActive=10
#???????????
maxWait=3000
#???????????sql
validationQuery=SELECT 1
#??????
testWhileIdle=true

JDBCUtilsByDruid.java:

package com.linghu.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * @Package: com.linghu.utils
 * @ClassName: JDBCUtilsByDruid
 * @Author: linghu
 * @CreateTime: 2023/3/30 16:27
 * @Description: 基于Druid(德鲁伊)的 JDBCUtils 工具类
 */
public class JDBCUtilsByDruid {
    
    


    private static  DataSource dataSource;

    static {
    
    
        Properties properties = new Properties();
        try {
    
    
            properties.load(new FileInputStream("src\\jdbc.properties"));
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
    }

    //方法1:获取德鲁伊连接池的“连接”的getConnection 方法
    public static Connection getConnection() throws SQLException {
    
    
        return dataSource.getConnection();
    }

    //方法2:断开与德鲁伊连接池的"连接"
    public static void close(ResultSet resultSet, Statement statement,Connection connection){
    
    
        try {
    
    
            if(resultSet != null){
    
    
                resultSet.close();
            }
            if (statement != null) {
    
    
                statement.close();
            }
            if (connection != null) {
    
    
                connection.close();
            }
        } catch (SQLException throwables) {
    
    
            throwables.printStackTrace();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43891901/article/details/130980037
今日推荐