JDBC和数据库连接池

2023-11-08

JDBC

基本介绍

在这里插入图片描述

JDBC原理

在这里插入图片描述

模拟JDBC

public class MysqlJdbcImp implements JdbcInterface{

    @Override
    public Object getConnection() {
        System.out.println("得到mysql的连接" );
        return null;
    }

    @Override
    public void crud() {
        System.out.println("得到mysql的增删改查" );
    }

    @Override
    public void close() {
        System.out.println("关闭连接" );
    }
}

public interface JdbcInterface {
    //连接
    public Object getConnection();
    //crud操作
    public void crud();
    //关闭连接
    public void close();
}
public class Test {
    public static void main(String[] args) {
        JdbcInterface jdbcInterface = new MysqlJdbcImp();
        jdbcInterface.getConnection();//通过接口来调用实现类
        jdbcInterface.crud();
        jdbcInterface.close();
    }
}

JDBC的API

在这里插入图片描述

JDBC程序编写步骤

在这里插入图片描述

package com.wcz_.jdbc;

import com.mysql.jdbc.Driver;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * @author 王成志
 * @version 1.0
 */
public class Jdbc01 {
    public static void main(String[] args) throws SQLException {
        //1.注册驱动
        Driver driver = new Driver();
        //2.得到连接
        //jdbc:mysql://规定好表示协议, 不能改变
        //localhost 表示主机,可以是ip地址
        //3306 表示mysql接听端口
        String url = "jdbc:mysql://localhost:3306/wcz_db02";
        //将用户名和密码封装到properties对象中
        Properties properties = new Properties();
        properties.setProperty("user","root");
        properties.setProperty("password","wcz");
        Connection connect = driver.connect(url, properties);//连接

        //3.执行sql
        String sql = "insert into actor values(null,'刘德华','男','1970-11-11','110' )";
        //用于执行静态sql语句并返回其生成的对象和结果
        Statement statement = connect.createStatement();
        int rows = statement.executeUpdate(sql);//如果是dml语句返回的就是影响行数
        System.out.println(rows > 0 ? "成功":"失败");
        //4.关闭连接
        statement.close();
        connect.close();
    }
}

JDBC连接数据库的方式

在这里插入图片描述
在这里插入图片描述

public void connect02() throws ClassNotFoundException, IllegalAccessException, InstantiationException, SQLException {
        Class<?> aClass = Class.forName("com.mysql.jdbc.Driver");
        Driver driver = (Driver) aClass.newInstance();
        String url = "jdbc:mysql://localhost:3306/wcz_db02";
        //将用户名和密码封装到properties对象中
        Properties properties = new Properties();
        properties.setProperty("user","root");
        properties.setProperty("password","wcz");
        Connection connect = driver.connect(url, properties);//连接
    }

在这里插入图片描述

//使用DriverManager替代Driver统一管理
    public void connect03() throws ClassNotFoundException, IllegalAccessException, InstantiationException, SQLException {
        Class<?> aClass = Class.forName("com.mysql.jdbc.Driver");
        Driver driver = (Driver) aClass.newInstance();
        //创建url
        String url = "jdbc:mysql://localhost:3306/wcz_db02";
        String user = "root";
        String password = "wcz";
        DriverManager.registerDriver(driver);//注册driver驱动
        DriverManager.getConnection(url,user,password);
    }

//方式4
    public void connect04() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        //创建url
        String url = "jdbc:mysql://localhost:3306/wcz_db02";
        String user = "root";
        String password = "wcz";
        Connection connection = DriverManager.getConnection(url, user, password);
    }

在这里插入图片描述

 public void connect05() throws IOException, ClassNotFoundException, SQLException {
        //通过properties对象获取信息
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\mysql.properties"));
        //获取相关值
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");

        String url = properties.getProperty("url");
        String driver = properties.getProperty("driver");
        Class.forName(driver);
        Connection connection = DriverManager.getConnection(url, user, password);

    }

ResultSet

在这里插入图片描述
在这里插入图片描述

statement

在这里插入图片描述

preparedstatement

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

JDBCUtils

在这里插入图片描述

public class JDBCUtils {
    //定义相关属性,只需要一份
    private static String user;//用户名
    private static String password;//密码
    private static String url;//url
    private static String driver;//驱动

    //在static代码块去初始化
    static {
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream("src\\mysql.properties"));
            user = properties.getProperty("user");
            password = properties.getProperty("password");
            url = properties.getProperty("url");
            driver = properties.getProperty("driver");
        } catch (IOException e) {
            //实际开发中可以这样处理
            throw new RuntimeException(e);
        }
    }

    //连接数据库
    public static Connection getConnection() {
        try {
            return DriverManager.getConnection(url, user, password);
        } catch (SQLException throwables) {
            throw new RuntimeException(throwables);
        }
    }

    //关闭相关资源
    /*
    1.ResultSet结果集
    2.Statement 或者 PreparedStatement
    3.Connection
     */
    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) {
            throw new RuntimeException(throwables;
        }
    }
}

在这里插入图片描述
在这里插入图片描述

事务

在这里插入图片描述

public class Transaction {
    @Test
    public void noTransaction(){
        //不用事务进行操作
        PreparedStatement preparedStatement =null;
        Connection connection = null;
        String sql = "update account1 set balance = balance - 100 where id = 1";
        String sql2 = "update account1 set balance = balance + 100 where id = 2";
        try {
            connection = JDBCUtils.getConnection();
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.executeUpdate();
            preparedStatement = connection.prepareStatement(sql2);
            preparedStatement.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            JDBCUtils.close(null,preparedStatement,connection);
        }

    }
    @Test
    public void useTransaction(){
        //使用事务进行
        PreparedStatement preparedStatement =null;
        Connection connection = null;
        String sql = "update account1 set balance = balance - 100 where id = 1";
        String sql2 = "update account1 set balance = balance + 100 where id = 2";
        try {
            connection = JDBCUtils.getConnection();
            //将connection设置为不自动提交
            connection.setAutoCommit(false);//相当于开启了事务
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.executeUpdate();
            int i = 1 / 0;
            preparedStatement = connection.prepareStatement(sql2);
            preparedStatement.executeUpdate();

        } catch (Exception e) {
            //在这边进行一个回滚
            try {
                connection.rollback();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            e.printStackTrace();
        } finally {
        }
    }
}


批处理

在这里插入图片描述

public class Batch {
    //演示批处理
    public void noBatch() throws SQLException {
        Connection connection = JDBCUtils.getConnection();
        String sql = "insert into admin2 values(null,?,?)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        for (int i = 0; i < 5000; i++) {
            preparedStatement.setString(1, "jack" + i);
            preparedStatement.setString(2, "666");
            preparedStatement.executeUpdate();
        }
        JDBCUtils.close(null, preparedStatement, connection);
    }

    public void useBatch() throws Exception {
        Connection connection = JDBCUtils.getConnection();
        String sql = "insert into admin2 values(null,?,?)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        for (int i = 0; i < 5000; i++) {
            preparedStatement.setString(1, "jack" + i);
            preparedStatement.setString(2, "666");
            //将sql语句加入批处理包
            preparedStatement.addBatch();
            //当有1000条时再执行
            if ((i + 1) % 1000 == 0){
                preparedStatement.executeBatch();
                // 清空
                preparedStatement.clearBatch();
            }
        }
        JDBCUtils.close(null, preparedStatement, connection);
    }
}

数据库连接池

基本介绍

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

连接种类

在这里插入图片描述
在这里插入图片描述

C3P0

//方式1相关参数在程序中指定
    @Test
    public void testC3P0_01() throws Exception{
        //创建一个数据源对象
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        //通过配置文件获取相关信息
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\mysql.properties"));
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        String url = properties.getProperty("url");
        String driver = properties.getProperty("driver");
        //给数据源comboPooledDataSource配置相关参数
        comboPooledDataSource.setDriverClass(driver);
        comboPooledDataSource.setJdbcUrl(url);
        comboPooledDataSource.setUser(user);
        comboPooledDataSource.setPassword(password);
        //设置初始化连接数
        comboPooledDataSource.setInitialPoolSize(10);
        //最大连接数
        comboPooledDataSource.setMaxPoolSize(50);
        Connection connection = comboPooledDataSource.getConnection();//核心方法
        System.out.println("连接成功");
        connection.close();
    }
   //第二种方法
    public void testC3P0_02() throws Exception{
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource("wcz_db02");
        Connection connection = comboPooledDataSource.getConnection();
        connection.close();
    }

druid

public class Druid_ {
    public void testDruid() throws Exception{
        //加入配置文件拷贝到src目录
        //读取配置文件
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\druid.properties"));
        //创建一个数据源
        DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
        Connection connection = dataSource.getConnection();
        connection.close();

    }

}

德鲁伊工具类

public class JDBCUtilsByDruid {
    private static DataSource 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放到连接池
    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) {
            throw new RuntimeException(throwables);
        }
    }
}

Apache——DBUtils

在这里插入图片描述
在这里插入图片描述

查询

public class DBUtils_Use {
    //使用apache的dbutils工具类完成crud
    @Test
    public void testQueryMany() throws SQLException {
        //得到连接
        Connection connection = JDBCUtilsByDruid.getConnection();
        //使用dbutils的类和接口,先引入jar文件
        //创建一个QueryRunner
        QueryRunner queryRunner = new QueryRunner();
        // 就可以执行相关方法
        String sql = "select * from actor where id >= ?";
        //query方法就是执行一个sql语句得到一个arraylist
        //beanlisthandler用来在将resultset取出来封装到arraylist
        //1是用来传给sql语句中的问号
        //底层会关闭resultset和statement
        List<Actor> list =
                queryRunner.query(connection, sql, new BeanListHandler<>(Actor.class), 1);
        for (Actor actor : list) {
            System.out.println(actor);//输出集合信息
        }
        JDBCUtils.close(null,null,connection);


    }
}

   @Test
    //演示返回结果是单行
    public void testQuerySimple() throws SQLException {
        //得到连接
        Connection connection = JDBCUtilsByDruid.getConnection();
        //使用dbutils的类和接口,先引入jar文件
        //创建一个QueryRunner
        QueryRunner queryRunner = new QueryRunner();
        // 就可以执行相关方法返回单个对象
        String sql = "select * from actor where id = ?";
        Actor actor =
                queryRunner.query(connection, sql, new BeanHandler<>(Actor.class),4);
        System.out.println(actor);
        JDBCUtils.close(null,null,connection);
    }

在这里插入图片描述

DML

@Test
    //演示完成dml操作
    public void testDML() throws SQLException {
        //得到连接
        Connection connection = JDBCUtilsByDruid.getConnection();
        //使用dbutils的类和接口,先引入jar文件
        //创建一个QueryRunner
        QueryRunner queryRunner = new QueryRunner();
        //组织sql语句完成dml
        String sql = "update actor set name = ? where id = ?";
        //返回的是生效行数
        int affectedRow = queryRunner.update(connection, sql, "rose", 4);
        System.out.println(affectedRow > 0?"执行成功":"无影响");
        JDBCUtils.close(null,null,connection);
    }

BasicDao

在这里插入图片描述

public class BasicDAO<T> {//泛型指定具体类型
    private QueryRunner qr = new QueryRunner();
    //开发通用的dml表
    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 throwables) {
            throw new RuntimeException(throwables);
        }finally {
            JDBCUtilsByDruid.close(null,null,connection);
        }

    }
    //返回多行查询
    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 throwables) {
            throw new RuntimeException(throwables);
        }finally {
            JDBCUtilsByDruid.close(null,null,connection);
        }

    }
    //查询单行
    public T querySimple(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 throwables) {
            throw new RuntimeException(throwables);
        }finally {
            JDBCUtilsByDruid.close(null,null,connection);
        }
    }
    //查询单行单列
    public Object queryScalar(String sql,Object... parameters){
        Connection connection = null;
        try {
            connection = JDBCUtilsByDruid.getConnection();
            return qr.query(connection,sql,new ScalarHandler(),parameters);
        } catch (SQLException throwables) {
            throw new RuntimeException(throwables);
        }finally {
            JDBCUtilsByDruid.close(null,null,connection);
        }
    }
}
public class TestDAO {
    //测试
    @Test
    public void testActorDAO(){
        ActorDAO actorDAO = new ActorDAO();
        //查询语句
        List<Actor> actors = actorDAO.queryMulti("select * from actor where id >= ?", Actor.class, 1);
        for (Actor actor : actors) {
            System.out.println(actor);
        }

    }
    
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

JDBC和数据库连接池 的相关文章

随机推荐

  • 简单文件数据库-模拟图书馆管理系统-西安电子科技大学大一程序基础设计课程设计作业

    命令行参数如下 Libsim a u xxxx 第一个参数为可执行程序名称 第二个参数为用户身份 a表示管理员 u表示读者 第三个参数为用户名 问题分析 由于无法直接在文件中插入数据 不是简单覆盖 固采用将文件数据提取为链表的方法 对链表进
  • Spring源码系列:Bean的加载

    Spring源码系列 Bean的加载 前言 一 Bean的加载 1 1 FactoryBean的使用 案例 FactoryBean的使用和定义 1 2 缓存中获取单例Bean 1 2 1 Spring解决循环依赖的原理 1 以A类的角度来观
  • 中间件Redis简介

    Redis概述 什么是redis Redis是一种支持key value等多种数据结构的高速缓存数据库 用C语言编写 可以用于缓存 事件发布和订阅 高速队列等场景 提供字符串 哈希 列表 队列 集合直接存存取 基于内存 可以持久化 为什么要
  • DeFi撑爆以太坊基础设施,近1亿美元BTC已进入以太坊生态

    编译 隔夜的粥 以太坊和DeFi在过去几个月里经历了爆炸性的增长 这已经不是什么秘密了 在过去2 3周里 它们已达到了一个全新的水平 各种应用的使用量增长如此之快 以至于给以太坊主要基础设施提供商TheGraph带来了巨大压力 导致其支持的
  • C中字符串操作

    字符串可以看作一个数组 它的每个元素是字符型的 例如字符串 Hello world n 图示如下 H e l l o w o r l d n 0 15个字符 注意每个字符串末尾都有一个字符 0 做结束符 这里的 0是ASCII码的八进制表示
  • 初识运营,明晰运营的学习路径

    关于运营的思考 问题1 运营是什么 运营到底是做什么工作的 如题 到底什么是运营 为什么我们所接触到的很多运营都不太一样 有的运营就是每天追寻互联网热点 加班加点的写文案 有的运营每天就是在不同的群里和成千上万的人唠嗑 有的运营活跃在不同的
  • html获取text输入框中的值

    1 在head中引用jquery 2 定义一个text输入框
  • 指针用作函数参数、指针型函数和函数指针

    指针用作函数参数 以前我们学过的函数参数要么是基本数据类型的变量 要么是类的对象 又或者是数组名 前几讲学到的指针同样可以用作函数参数 指针作函数形参时 我们调用此函数将实参值传递给形参后 实参和形参指针变量将指向相同的内存地址 那么在被调
  • Linux主要命令功能

    1 dmesg 主要用来显示内核信息 使用dmesg可以有效诊断机器硬件故障或者添加硬件出现的问题 另外使用dmesg可以确定你的服务器安装了那些硬件 每次系统重启 系统都会检查所有硬件并将信息记录下来 执行 bin dmesg命令可以查看
  • 第十届蓝桥杯真题-灵能传输

    题目 OJ https www lanqiao cn problems 196 learning 考点 前缀和 贪心 思路 题目意思就是希望通过灵能交换后使得不稳定度最小 假设对a i 进行灵能传输 可以发现前缀和s i 1 和s i 进行
  • Java值传递和引用传递详细说明(详细分析)

    1 形参与实参 我们先来重温一组语法 形参 方法被调用时需要传递进来的参数 如 func int a 中的a 它只有在func被调用期间a才有意义 也就是会被分配内存空间 在方法func执行完成后 a就会被销毁释放空间 也就是不存在了 实参
  • FormData同时传输多个文件和其他数据

    近日有个需求是 在web的对话框中 用户可以输入文本内容和上传附件 附件的数量不限 所有附件总和大小不超过20M 这个实现的方法不止一种 比如之前的后端同事是要求 文件和文本分开传输 文件用一个单独接口上次 上传成功后返回一个id 把这个i
  • 【论文翻译】Iterative Geometry Encoding Volume for Stereo Matching and Multi-View Stereo(CVPR 2023)

    一 论文简述 1 第一作者 Gangwei Xu 2 发表年份 2023 3 发表期刊 CVPR 4 关键词 立体匹配 MVS 几何编码体 GRU 3D卷积 5 探索动机 RAFT的全对相关体缺乏非局部几何知识 难以处理病态区域的局部模糊
  • perp系列之五:perp安装

    perp系列之五 perp安装 版本说明 版本 作者 日期 备注 0 1 ZY 2019 5 29 初稿 目录 文章目录 perp系列之五 perp安装 版本说明 目录 概要 描述 激活 升级 例子 概要 vi conf mk make m
  • Vmware虚拟机设置静态IP地址

    一 安装好虚拟后在菜单栏选择编辑 虚拟网络编辑器 打开虚拟网络编辑器对话框 选择Vmnet8 Net网络连接方式 随意设置子网IP 点击NAT设置页面 查看子网掩码和网关 后面修改静态IP会用到 二 检查宿主机VM8 网卡设置 打开网络和共
  • 欧科云链OKLink:2023年6月安全事件盘点

    一 基本信息 2023年6月REKT和RugPull事件约造成约1000万美元损失 相比上月有显著下降 但安全事件发生数量依旧不减 其中被废弃的Atlantis Loans遭受治理攻击 造成的损失超250万美元 对该协议有过授权的用户需及时
  • Faster R-CNN详解

    Faster R CNN代码实现详解参见 faster rcnn源码详解 樱花的浪漫的博客 CSDN博客 faster rcnn源码 Faster rcnn详细注释版源码地址 faster rcnn源码详细注释版 每一步均有详细批注 深度学
  • 目标检测 实践

    文章目录 0 数据标注via 一 添加图片 二 定义标记类型 Attributes 三 标注 四 导出标注文件 1 模型 1 1 数据准备 1 2 模型训练 1 3 模型使用 1 4 改进方向 0 数据标注via via工具的界面如下图所示
  • python3中多项式创建_利用 Python3 ,实现数学科学计算

    SymPy是符号数学的Python库 旨在用一套强大的符号计算体系完成诸如多项式求值 求极限 解方程 求积分 微分方程 级数展开 矩阵运算等等计算问题 虽然Matlab的类似科学计算能力也很强大 但是Python以其语法简单 易上手 异常丰
  • JDBC和数据库连接池

    JDBC 基本介绍 JDBC原理 模拟JDBC public class MysqlJdbcImp implements JdbcInterface Override public Object getConnection System o