• JDBC学习


    目录

    1.什么是JDBC?

    2.JDBC的操作步骤

    3.JDBC实现CRUD

    4.JDBC的驱动加载(Driver)

    5.SQL注入

    6.JDBC中的核心对象

    7.JDBC事务操作

    1.三层架构

    2.连接池

    3.Spring-JDBC


    1.什么是JDBC?

    JDBC全称是Java Database Connectivity(java数据库连接),是java连接数据库的标准和规范。

    2.JDBC的操作步骤

    1.导入驱动包

    2.加载驱动

    3.打开连接

    4.获取预处理器

    5.设置参数

    6.执行SQL

    7.解析结果

    8.关闭连接

    3.JDBC实现CRUD

    package com.qu.demo01;
    ​
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.SQLException;
    ​
    /**
     * JDBC新增操作
     */
    public class Demo01 {
        public static void main(String[] args) throws SQLException {
            Connection connection = null;
            try {
                //    2.加载驱动
    //        5版本   com.mysql.jdbc.Driver
    //        8版本   com.mysql.cj.jdbc.Driver
                Class.forName("com.mysql.cj.jdbc.Driver");
    ​
    //        3.打开连接
                connection =  DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc?serverTimezone=UTC", "root", "123456");
    //       4.获取预处理器
                PreparedStatement preparedStatement = connection.prepareStatement("insert into t_user(id,name) values(?,?)");
    //       5.设置参数
    //        setInt(第几个参数,值);
                preparedStatement.setInt(1,5);
                preparedStatement.setString(2,"赵六");
    //            6.执行SQL
               preparedStatement.execute();
    //            7.解析结果
    ​
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }finally {
    //            8.关闭连接
                connection.close();
            }
        }
    }

    4.JDBC的驱动加载(Driver)

    三种写法:

    1.Class.forName(“xxx”); (用的最多)

    2.DriverManager.registerDriver(new Driver());//重复加载

    3.不显示加载驱动类 //依赖包的配置文件,有的jar包没有该文件

    5.SQL注入

    什么是SQL注入?

    SQL注入是利用SQL拼接的特点而实现的一种攻击方式

    SQL注入的案例

    package com.qu.demo01;
    ​
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.util.Scanner;
    ​
    /**
     * SQL注入
     */
    public class Demo05 {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            System.out.println("请输入登录的用户名:");
            String name = sc.nextLine();
            System.out.println("请输入登录的密码:");
            String pwd = sc.nextLine();
    ​
            try {
                System.out.println(pwd);
                Connection connection = DriverManager.getConnection("jdbc:mysql:///jdbc?serverTimezone=UTC", "root", "123456");
                String sql = "select * from t_user where name='"+name+"' and pwd = '"+pwd+"'";
                //        a' or 'a' = 'a (前后会补充' ')
                PreparedStatement preparedStatement = connection.prepareStatement(sql);
                ResultSet resultSet = preparedStatement.executeQuery();
                if (resultSet.next()){
                    System.out.println("登录成功");
                }else{
                    System.out.println("登录失败");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    防止SQL注入的方法

    使用?占位符形式设置参数

    防止SQL注入的原理

    内部对参数进行了处理

    package com.qu.demo01;
    ​
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.util.Scanner;
    ​
    /**
     * SQL注入 防止破解 用?:内部对参数进行了处理
     */
    public class Demo06 {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            System.out.println("请输入登录的用户名:");
            String name = sc.nextLine();
            System.out.println("请输入登录的密码:");
            String pwd = sc.nextLine();
    ​
            try {
                System.out.println(pwd);
                Connection connection = DriverManager.getConnection("jdbc:mysql:///jdbc?serverTimezone=UTC", "root", "123456");
                String sql = "select * from t_user where name= ? and pwd = ?";
                PreparedStatement preparedStatement = connection.prepareStatement(sql);
                preparedStatement.setString(1,name);
                preparedStatement.setString(2,pwd);
                ResultSet resultSet = preparedStatement.executeQuery();
                if (resultSet.next()){
                    System.out.println("登录成功");
                }else{
                    System.out.println("登录失败");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    6.JDBC中的核心对象

    1.DriverManager:驱动管理(驱动的注册,打开连接)

    2.Connection:连接(控制连接,处理事务)

    3.PreparedStatement:设置参数、执行SQL

    PreparedStatement和Statement的联系与区别?

    联系:两者都是处理器对象,都是负责执行SQL语句,PreparedStatement是Statement的子接口,拥有更丰富的API

    区别:PreparedStatement可以防止SQL注入,Statement不可以

    4.ResultSet:结果集(封装了查询语句中返回的所有数据)

    7.JDBC事务操作

    1.设置手动提交

    connection.setAutoCommit(false);

    2.提交事务

    connection.commit();

    3.回滚事务

    connection.rollback();

    第二部分

    1.三层架构

    三层架构是一种软件设计架构,是一种组织代码的手段和方式。

    表示层(UI):数据的显示或者数据的录入(注册界面/转账界面)

    业务层(BLL):业务的具体操作流程(控制事务)(注册/转账)

    持久层(DAL):提供数据库表的CRUD(用户表的CRUD)

    三层架构的缺点:步骤多,代码多,效率降低

    三层架构优点:扩展性,复用性

    view->service->dao
    ​
    写的顺序是dao->service->view
    ​
    先写接口再写实现类
    创建一个集合(集合里面放对象(entity))

    目录说明:dao:持久层

    entity:实体类

    service:业务层

    utils:工具类

    view:表示层

    2.连接池

    1.连接池的定义:一种存放数据库连接的容器,并且拥有动态新增连接,管理连接等功能于一体的容器(类似于共享充电宝)

    2.为什么要使用连接池?

    加快连接的获取速度

    合理的应用连接

    3.连接池的分类

    dbcp

    c3p0

    druid

    hikaricp √

    ...

    连接池的核心对象

    DataSource

    hikaricp连接池的使用

    1.导包

    2.创建连接池对象

    3.从连接池中获取连接

    4.使用连接

    5.回收连接

    将连接池整合到DBUtils工具类中

    3.Spring-JDBC

    一个由Spring团队开发的JDBC的工具类。作用和DBUtils一样,是目前代替DBUtils产物

    使用步骤:

    1.导包

    2.创建JdbcTemplate工具

    3.使用JdbcTemplate完成CRUD操作

    package com.blb.demo02;
    ​
    import com.zaxxer.hikari.HikariConfig;
    import com.zaxxer.hikari.HikariDataSource;
    import org.springframework.jdbc.core.BeanPropertyRowMapper;
    import org.springframework.jdbc.core.JdbcTemplate;
    ​
    import java.io.IOException;
    import java.util.List;
    import java.util.Properties;
    ​
    public class Demo01 {
        public static void main(String[] args) throws IOException {
    //        1.创建连接池
            Properties properties = new Properties();
            properties.load(Demo01.class.getClassLoader().getResourceAsStream("jdbc.properties"));
            HikariConfig hikariConfig = new HikariConfig(properties);
            HikariDataSource hikariDataSource = new HikariDataSource(hikariConfig);
    ​
    //        2.创建JdbcTemplate
            JdbcTemplate jdbcTemplate = new JdbcTemplate(hikariDataSource);
    ​
    //        3.使用jdbcTemplate
    //        查询用户表的总条数
            Integer count = jdbcTemplate.queryForObject("select count(*) from t_user", Integer.class);
            System.out.println(count);
    ​
    //        添加用户
    //        jdbcTemplate.update("insert into t_user(name,pwd) values (?,?)","张三","123456");
    ​
    //        删除用户
    //        jdbcTemplate.update("delete from t_user where id = ?","6");
    ​
    //        更新用户
    //        jdbcTemplate.update("update t_user set name = ? where id = ?","张张","5");
    ​
    //        查询所有用户
            List list = jdbcTemplate.query("select * from t_user", new BeanPropertyRowMapper(User.class));
            System.out.println(list);
        }
    }

  • 相关阅读:
    github访问慢怎么办
    2023年6月电子学会Python等级考试试卷(五级)答案解析
    技术资料:STM32F746NGH7,STM32L471ZGT6 IC MCU+FPU
    原生js--封装点击上传附件
    安全开发实战(2)---域名反查IP
    基于MFC和OpenCV实现人脸识别
    git合并错分支还原技巧
    【深度学习】MNIST手写数字数据集的分类识别
    生成 小程序 URL Scheme
    Linux系统中安装Redis并设置开机
  • 原文地址:https://blog.csdn.net/qq_60154877/article/details/126386965