• JDBC实用详解


    📖个人介绍


    大家好我是:一颗松
    认真分享技术,记录学习点滴
    如果分享对你有用请支持我哦🍺

    点赞:👍 留言:✍收藏:⭐️
    个人格言: 想法落实的最佳时机就是现在!🏄


    在这里插入图片描述

    :::info
    💡 概念:JDBC是java提供的一套用于操作数据库的接口API:java程序员只需要面向这套接口编程即可;
    :::

    java连接数据库有五种方式:①静态加载②使用反射动态加载

    1 JDBC静态加载,的使用步骤

    1.1 注册驱动【加载Driver类】

    Driver driver = new Driver();
    
    • 1

    1.2 获取连接【得到Connection】

    Properties properties = new Properties();
    String url = "jdbc:mysql://127.0.0.1:3306/school";
    properties.setProperty("user","root");
    properties.setProperty("password","123456");
    Connection connect = driver.connect(url, properties);
    
    • 1
    • 2
    • 3
    • 4
    • 5

    1.3 执行增删改查【发送SQL命令】

            String sql = "create table test";
            Statement statement = connect.createStatement();
            statement.executeUpdate(sql);
            
    
    • 1
    • 2
    • 3
    • 4

    1.4 释放资源

     
            connect.close();
            statement.close();
    
    • 1
    • 2
    • 3

    2 反射动态加载数据库

    //    方式2 动态加载[使用反射加载driver类]
    //        加载driver的Class对象
            Class<?> aClass = Class.forName("com.mysql.jdbc.Driver");
            Driver driver = (Driver) aClass.newInstance();
    //        2得到连接
            String url = "jdbc:mysql://127.0.0.1:3306/school";
            Properties properties = new Properties();
            properties.setProperty("user", "root");
            properties.setProperty("password", "123456");
            Connection connect = driver.connect(url, properties);
    //        3执行SQL
            String sql = "delete from person where id = 2";
    //        创建statement对象
            Statement statement = connect.createStatement();
            int i = statement.executeUpdate(sql);
            System.out.println(i > 0 ? "成功" : "失败!");
    //        4关闭资源
            connect.close();
            statement.close();
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    3 使用DriverManager统一管理

    //        方式3 使用DriverManager注册驱动,进行统一管理
    //        1 注册驱动
            Class<?> aClass = Class.forName("com.mysql.jdbc.Driver");
            Driver driver = (Driver) aClass.newInstance();
            String url = "jdbc:mysql://localhost:3306/school";
            String user = "root";
            String password = "123456";
            DriverManager.registerDriver(driver);//注册driver驱动
    //        2获取Connetion
            Connection connection = DriverManager.getConnection(url, user, password);
    //        3 执行SQL操作
            String sql = "insert into person value (1,'韩顺平',99,88,98)";
            Statement statement = connection.createStatement();
            int i = statement.executeUpdate(sql);
            System.out.println(i>0 ? "成功":"失败");
    //        3 关闭资源
            connection.close();
            statement.close();
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    4 推荐使用

    //        方式4  使用Class.forName() 自动完成驱动,简化代码,
    //        1 自动完成驱动注册
            Class<?> aClass = Class.forName("com.mysql.jdbc.Driver");
    //        创建url、user 、password
            String url = "jdbc:mysql://localhost:3306/school";
            String user = "root";
            String password = "123456";
    //        2 创建连接
            Connection connection = DriverManager.getConnection(url, user, password);
    //        3 执行SQL
            String sql = "insert into person value (2,'zsl',99,88,88)";
            Statement statement = connection.createStatement();
            int i = statement.executeUpdate(sql);
            System.out.println(i>0 ? "成功":"失败");
    //        4 关闭资源
            connection.close();
            statement.close();
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    5 ResultSet类的使用

    5.1 基本介绍

    (1)表示数据库结果集的一个数据表,通常通过执行select语句生成
    (2)ResultSet保持一个光标,指向当前数据行,最初光标位于第一行之前
    (3)next方法将光标移到下一行,当在ResultSet对象没有下一行对象时返回false

         //    ResultSet类的使用
            //        获取配置文件信息
            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");
    //       1 注册驱动
            Class<?> aClass = Class.forName(driver);
            Driver driver1 = (Driver) aClass.newInstance();
    //       2 创建连接
            Connection connection = DriverManager.getConnection(url, user, password);
    //        3 执行SQL语句select语句
            String sql = "select * from person ";
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery(sql);
            while (resultSet.next()){
                int id = resultSet.getInt(1);
                String name = resultSet.getString(2);
                int Chinese = resultSet.getInt(3);
                System.out.println(id+"\t"+name+"\t"+Chinese);
            }
    //        4 关闭资源
            connection.close();
            statement.close();
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    6 预处理PreparedStatement,与Statement相比更安全避免了SQL注入

    // PreparedStatement预处理使用
            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");
    //       1 注册驱动
            Class<?> aClass = Class.forName(driver);
            Driver driver1 = (Driver) aClass.newInstance();
    //       2 创建连接
            Connection connection = DriverManager.getConnection(url, user, password);
    //        3 执行SQL语句select语句
            String na = "admin";
            String pw = "123";
    //        SQL语句中的?相当与站位符
            String selectSql = "select id from user where `name` =? and pwd = ?";
            String addSql =  "insert into user value('001','admin','123')";
            String createTable = "create table  user ( id varchar(10),`name` varchar(10),pwd varchar(10))";
            PreparedStatement preparedStatement = connection.prepareStatement(selectSql);
            preparedStatement.setString(1,na);
            preparedStatement.setString(2,pw);
    //        int i = preparedStatement.executeUpdate();
    //        System.out.println(i>0? "成功":"失败");
            ResultSet resultSet = preparedStatement.executeQuery();
            System.out.println(resultSet);
                while (resultSet.next()){
                    String id = resultSet.getString(1);
                    System.out.println(id);
                }
    //        4 关闭资源
            connection.close();
          preparedStatement.close();
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33

    7 JDBC事务处理

    1)在JDBC程序中当Connection对象创建时,默认情况下自动提交事务,没执行成功一次sql语句,自动提交不能回退
    (2)在JDBC程序中为了让多个语句成为一个整体,需要用到事务
    (3)调用Connection的setAutoCommit(false)可以取消自动提交事务
    (4)所有SQL语句执行后,调用commit() 方法提交事务
    (5)在其中的某个操作失败或者出现异常时,调用rollback()方法回退事务;

    8 JDBC的SQL语句批处理

    基本介绍:
    (1):当需要成批的删除或者添加数据时,可以采用java的批量更新机制;
    (2):JDBC的批量处理包含以下方法:
    ①:addBatch();添加需要批处理的SQL语句或参数;
    ②:executeBatch();执行批处理语句
    ③:JDBC连接mysql时,如果需要批处理,在 url中添加参数 :
    ?rewriteBatchedStatements=true
    ④:批处理往往和PreparedStatement一起搭配使用

     public void batch(){
            Connection conection = JDBCUtils.getConection();
            String sql = "insert into admain value(?,?,?)";
            PreparedStatement preparedStatement = null;
            try {
                preparedStatement = conection.prepareStatement(sql);
                System.out.println("开始执行!");
                long starr = System.currentTimeMillis();
                for (int i = 0; i <= 1000; i++) {
                    preparedStatement.setInt(1,i);
                    preparedStatement.setString(2,"小明"+i);
                    preparedStatement.setString(3,"123"+i);
    //                将SQL语句加入批处理中
                    preparedStatement.addBatch();
    //                当有111条语句时批量执行
                    if (i%100==0){//执行语句满111
    //                    批量执行
                        preparedStatement.executeBatch();
    //                    清空
                        preparedStatement.clearBatch();
                    }
                }
                long end = System.currentTimeMillis();
                System.out.println("批量处理执行时间:"+(end-starr));
            } catch (SQLException e) {
                e.printStackTrace();
            }
            JDBCUtils.getClose(preparedStatement,conection,null);
    
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30

    结语

    大佬请留步在这里插入图片描述既然看到这了不如点个赞👍再走吧

    本文目的在于分享技术以及在学习过程中个人记得需要注意的点,记录学习过程;
    如果出现错误欢迎大家指正,如有意见或建议欢迎在评论区讨论

  • 相关阅读:
    easyexecl导出100万行execl报字体错误的解决办法
    【iOS】使用respondsToSelector方法前是否需要对方法调用者进行判空操作?
    【算法练习Day31】单调递增的数字&&买卖股票的最佳时机含手续费&&监控二叉树
    Linux:冯诺依曼系统和操作系统的概念
    【Shell牛客刷题系列】SHELL17 将字段逆序输出文件的每行:巩固awk命令与学习反向列示文件内容的tac命令
    天猫精灵、Blinker 控制esp32自带灯熄灭---Micropython版本
    Sql中having和where的区别
    猿如意开发工具|Sublime Text(4126)
    JAVA计算机毕业设计蔬菜水果销售系统源码+系统+mysql数据库+lw文档
    苹果 MAC 电脑 boot camp 助手装 Windows10 双系统出现的各种问题和解决方法
  • 原文地址:https://blog.csdn.net/Zinkse/article/details/126274833