JDBC概述

image

基本介绍

image

基本原理图

image

jdbc带来的好处

image

jdbc的api

image

快速入门

jdbc编写步骤

image

前置工作.在项目文件中创建一个新文件夹libs,把mysql.jar压缩包复制进去,然后把压缩包加入项目里, add as library
image
image
image

image

image

连接数据库的五种方式

image

image

image
看不懂啥事静态加载和动态 复习 反射章节的类加载片段

image
newinstance过时了 就先getConstructor().newinstance();

第四种方式是使用最多的,最推荐的

image

driver源码
image

第四种升级版

image

第五种是第四种方式的优化版

image

image

resultset底层

基本介绍

image

流程

image
image

resultset源码分析
image

image

sql注入

image

案例

image

image

image

resultset关闭 statement关闭 connection关闭

预处理查询(解决sql注入问题)

image

image

image

案例(得到的是preparedStatement)

image

image
当然如果你上面的sql语句就是真确的值的话,就可以填入
image

预处理dml(注意和select语句区别即可)

image
image

JDBCAPI

思维导图

image
PreparedStatement接口有d 方法没d,所以笔记中没错

JDBCUtils开发

image

示意图

image
减少代码的冗余

韩顺平833

idea项目里面
忘记了 select和dml操作 看 utils的具体方法

事务(不明白回看mysql事务)

image

实例

image

批处理应用

image

示意图

image
批处理比作一辆小客车,载满100人才出发,然后到终点了,人全部下车(清空),才重新回来载客 ,案例在idea里面

源码分析(addbatch)

image
image

数据库连接池

传统连接弊端分析

image

image

案例

image

连接池示意图

image

image

连接池种类

image

C3P0(老牌连接池,掌握使用方法)

两种方式

public class C3P0 {
    @Test
    public void testC3P0_01() throws Exception {
        //1.创建一个数据源对象
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        //2.通过配置文件获得文件信息
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\mysql.properties"));
        //获取相应的值
        String user = properties.getProperty("user");
        String password =properties.getProperty("password");
        String driver = properties.getProperty("driver");
        String url = properties.getProperty("url");

        //给数据源设置相关参数
        //注意: 连接管理是由comboPooledDataSource来管理
        comboPooledDataSource.setDriverClass(driver);
        comboPooledDataSource.setJdbcUrl(url);
        comboPooledDataSource.setUser(user);
        comboPooledDataSource.setPassword(password);

        //设置初始化连接数
        comboPooledDataSource.setInitialPoolSize(10);
        //设置最大连接数
        comboPooledDataSource.setMaxPoolSize(50);
        //测试连接池效率
        long start = System.currentTimeMillis();
        for (int i = 0; i <5000 ; i++) {

            Connection connection = comboPooledDataSource.getConnection();//这个方法就是从 DataSource接口实现的
            connection.close();
        }
        long end = System.currentTimeMillis();
        System.out.println("C3P0耗时="+(end-start));//耗时=469
    }

常用第二种,方便

//第二种方式 使用配置模板来完成

    //1.将cp30提供的config.xml 拷贝到 src
    //2. 该文件指定了相关参数,注意必须放到src

    @Test
    public void test_c3p0_02() throws SQLException {
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource("lyq_stu");

        long start = System.currentTimeMillis();
        //测试5000次连接mysql
        for (int i = 0; i <5000; i++) {
            Connection connection = comboPooledDataSource.getConnection();
            //System.out.println("连接成功");
            connection.close();
        }
        long end = System.currentTimeMillis();
        System.out.println("cp30使用第二种方式耗时="+(end-start));


    }
}

Druid实例(现阶段最牛连接池,开发推荐使用)

public class Druid {
    @Test
    public void testDruid() throws Exception {
        //1、加入 Druid jar包
        //2  加入配置文件 druid.properties,拷贝到src
        //3. 创建一个properties对象,获取文件信息
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\druid.properties"));

        //4.创建一个指定参数的数据库连接池
        DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
        long start = System.currentTimeMillis();
        for (int i = 0; i <500000 ; i++) {
            Connection connection = dataSource.getConnection();
            //System.out.println("连接成功");
            connection.close();
        }
        long end = System.currentTimeMillis();
        System.out.println("使用druid连接池(500000)耗时="+(end-start));//714
    }
}
德鲁伊工具类
apache——DBUtils

image

示意图
image

image
实际上就是把返回集的结果封装到ArrayList集合当中了

老师的土方法
{
        System.out.println("使用Druid方式完成");
        //获得连接
        Connection connection = null;

        //查询语句
        String sql = "select * from actor where  id = ?";
        ResultSet resultSet = null;
        PreparedStatement preparedStatement = null;
        ArrayList<Actor> list = new ArrayList<Actor>();//创建ArrayList对象,存放actor
        //新建preparestatement对象
        try {
            connection = JDBCUtilsByDruid.GetConnection();
            System.out.println(connection.getClass());
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,"8");
            //执行得到结果集
            resultSet = preparedStatement.executeQuery();
            //遍历结果集
            while (resultSet.next()){
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                String sex = resultSet.getString("sex");
                Date borndate = resultSet.getDate("borndate");
                String phone = resultSet.getString("phone");
                list.add(new Actor(id,name,sex,borndate,phone));
            }
            //System.out.println("list集合数据+"+list);
            for (Actor actor:list){
                System.out.println("id="+actor.getId() +"\t"+"name="+actor.getName());
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtilsByDruid.close(resultSet,preparedStatement,connection);
        }
        //因为ArrayList 和 connect没有任何关联,所以可以复用
        return list;
    }
真正的方法

image

代码案例(重要的就在源码分析那块,其他熟悉用法ok)
package com.hspedu.jdbc.datasource;

import com.hspedu.jdbc.utlis.JDBCUtilsByDruid;
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 org.junit.Test;

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

/**
 * @author lyq
 * @version 1.0
 */
public class DButils_USE {

    //使用apache——DBUtils 工具类 + druid 完成对表的CRUD操作
    @Test
    public void testQueryMany() throws SQLException { //返回结果是多行
        Connection connection = JDBCUtilsByDruid.GetConnection();

        //2. 使用 DBUtils 类和接口 , 先引入 DBUtils 相关的 jar , 加入到本 Project
        //3. 创建 QueryRunner

        QueryRunner queryRunner = new QueryRunner();

        //4. 就可以执行相关的方法,返回 ArrayList 结果集
        String sql  = "select * from actor where id >= ?";
        // 老韩解读
        //(1) query 方法就是执行 sql 语句,得到 resultset ---封装到 --> ArrayList         集合
		//(2) 返回集合
        //(3) connection: 连接
        //(4) sql : 执行的 sql 语句
        //(5) new BeanListHandler<>(Actor.class): 在将 resultset -> Actor 对象 -> 封装到 ArrayList
        //底层使用反射机制 去获取 Actor 类的属性,然后进行封装
        //(6) 1 就是给 sql 语句中的? 赋值,可以有多个值,因为是可变参数 Object... params
        //(7) 底层得到的 resultset ,会在 query 关闭, 关闭 PreparedStatment
        /**
         * 分析 queryRunner.query 方法:
         * public <T> T query(Connection conn, String sql, ResultSetHandler<T> rsh, Object... params) throws
         SQLException {
         *
         PreparedStatement stmt = null;//定义 PreparedStatement
         *
         ResultSet rs = null;//接收返回的 ResultSet
         *
         Object result = null;//返回 ArrayList
         *
         *
         try {
         *
         stmt = this.prepareStatement(conn, sql);//创建 PreparedStatement
         *
         this.fillStatement(stmt, params);//对 sql 进行 ? 赋值
         *
         rs = this.wrap(stmt.executeQuery());//执行 sql,返回 resultset
         *
         result = rsh.handle(rs);//返回的 resultset --> arrayList[result] [使用          到反射,对传入 class 对象
         处理]
         *
         } catch (SQLException var33) {
         *
         this.rethrow(var33, sql, params);
         *
         } finally {
         *
         try {
         *
         this.close(rs);//关闭 resultset
         *
         } finally {
         *
         this.close((Statement)stmt);//关闭 preparedstatement 对象
         *
         }
         *
         }
         *
         *
         return result;
         *
         }
         */

        List<Actor> list =
                queryRunner.query(connection, sql, new BeanListHandler<>(Actor.class), 0);
        System.out.println("输出集合的信息");
        for (Actor actor:list){
            System.out.println(actor);
        }

        //释放资源
        JDBCUtilsByDruid.close(null,null,connection);

    }

    //演示apache——dbutils + druid 完成返回结果是单行的对象
    @Test
    public void testQuerySingle() throws SQLException {
        //得到连接
        Connection connection = JDBCUtilsByDruid.GetConnection();
        //2. 使用 DBUtils 类和接口 , 先引入 DBUtils 相关的 jar , 加入到本 Project
        //3. 创建 QueryRunner
        QueryRunner queryRunner = new QueryRunner();
        //执行相关方法
        String sql = "select * from actor where id = ?";
        //因为返回的是单行对象,使用的Hander是BeanHander
        Actor actor =
                queryRunner.query(connection, sql, new BeanHandler<>(Actor.class), 1);
        System.out.println(actor);
        //关闭连接
        JDBCUtilsByDruid.close(null,null,connection);

    }

    //演示 apache+Druid 完成查询结果的单行单列   核心代码就是返回的类型的时候不同
    @Test
    public void testScalar() throws SQLException {
        Connection connection = JDBCUtilsByDruid.GetConnection();
        //2. 使用 DBUtils 类和接口 , 先引入 DBUtils 相关的 jar , 加入到本 Project
        //3. 创建 QueryRunner
        QueryRunner queryRunner = new QueryRunner();
        //执行相关方法
        String sql = "select  name from actor where id = ?";
        //因为返回的是单行单列,所以Handler用的是ScalarHandler
        Object obj = queryRunner.query(connection, sql, new ScalarHandler<>(), 8);
        System.out.println(obj);
        //关闭连接
        JDBCUtilsByDruid.close(null,null,connection);

    }

    //演示的是 apache + Durid 演示  insert,delete,update
    @Test
    public void testDML() throws SQLException {
        Connection connection = JDBCUtilsByDruid.GetConnection();
        //2. 使用 DBUtils 类和接口 , 先引入 DBUtils 相关的 jar , 加入到本 Project
        //3. 创建 QueryRunner
        QueryRunner queryRunner = new QueryRunner();
        //执行相关方法
        //String sql = "update  actor set name = ? where id = ? ";
        //String sql = "insert into actor values (null ,?,?,?,?)";
        String sql = "delete from  actor where id = ?";
        //这里就是和select不一样的地方,select是返回集,这里是受影响的行数
        //(2) 返回的值是受影响的行数 (affected: 受影响
        // int affectedROW = queryRunner.update(connection,sql,"王富贵",8);
        //int affectedROW = queryRunner.update(connection,sql,"紫霞仙子","女","1990-12-1","520");
        int affectedROW = queryRunner.update(connection,sql,"1");
        System.out.println(affectedROW>0 ? "执行成功" : "执行没有影响到表");

        //关闭连接
        JDBCUtilsByDruid.close(null,null,connection);
    }
}

BasicDao

image

示意图
image

image

应用实例

image

posted @   java同学!  阅读(50)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示