• JDBC详解


    活动地址:CSDN21天学习挑战赛
    在这里插入图片描述
    🍁博客主页:👉@不会压弯的小飞侠
    欢迎关注:👉点赞👍收藏留言
    系列专栏:👉21天挑战回顾java
    知足上进,不负野心。
    🔥欢迎大佬指正,一起学习!一起加油!

    在这里插入图片描述


    一、jdbc入门案例

    • 创建工程,导入驱动jar包
      • mysql-connector-java-5.1.48.jar
    • 1.注册驱动
      • Class.forName(“com.mysql.jdbc.Driver”);
    • 2.获取连接
      • Connection conn = DriverManager.getConnection(url, username, password);
    • 3.定义SQL语句
      • String sql = “update…”" ;
    • 4.获取执行SQL对象
      • Statement stmt = conn.createStatement();
    • 5.执行SQL
      • stmt.executeUpdate(sql);
    • 6.处理返回结果
    • 7.释放资源

    案例:

    package com.study;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.Statement;
    public class TestOne {
        public static void main(String[] args) throws Exception {
            //注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            //获取连接
            String url="jdbc:mysql://localhost/jdbcone";
            String userName="root";
            String passWord="root";
            Connection conn = DriverManager.getConnection(url, userName, passWord);
            //定义sql
            String sql="update users set password=666 where id=1";
            //获取执行sql的statement对象
            Statement stmt = conn.createStatement();
            //执行sql
            int count = stmt.executeUpdate(sql); //受影响的行数
            //处理结果
            System.out.println("受影响的行数:"+count);  //受影响的行数:1
            //释放资源
            stmt.close();
            conn.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

    二、JDBC-API详解

    1.DriverManager

    • 1.注册驱动

      • Class.forName(“com.mysql.jdbc.Driver”);
    • 提示:

      • MySQL 5之后的驱动包,可以省略注册驱动的步骤
      • 自动加载jar包中META-INF/services/java.sql.Driver文件中的驱动类
    • 2.获取连接

      • static connection getconnection (String url,String user,String password)
    • 参数

      • 1.url:连接路径
      • 语法: jdbc:mysql-/ip地址(域名):端口号:/数据库名称?参数键值对1&参数键值对
      • 示例: jdbc:mysql:127,0.0.1:3306/db1
      • 细节:
      • 如果连接的是本机mysq服务器,并目mysql服务默认端口是3306,则luri可以简写为: jdbc:mysqt!:l数据库名称?参数键值对·配置useSSL=false参数,禁用安全连接方式。解决警告提示
        1. user:用户名
        1. password:密码

    2.Connection

    • 1.获取执行SQL的对象
      • 普通执行SQL对象
      • statement createStatement()
      • 预编译SQL的执行SQL对象:防止SQL注入
      • PreparedStatement prepareStatement (sql)
      • 执行存储过程的对象
      • CallableStatement prepareCall (sql)
    • 2.事务管理
      • MySQL事务管理
      • 开启事务:BEGIN; START TRANSACTION;
      • 提交事务:COMMIT;
      • 回滚事务:ROLLBACK;
      • MySQL默认自动提交事务
      • JDBC 事务管理:Connection接口中定义了3个对应的方法
      • 开启事务: setAutoCommit(boolean autoCommit): true为自提交事务;false为手动提交事务,即为开启事务
      • 提交事务: commit()
      • 回滚事务: rollback()

    案例:

    package com.study;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.sql.Statement;
    public class TestOne {
        public static void main(String[] args) throws Exception {
            //注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            //获取连接
            String url="jdbc:mysql://localhost/jdbcone";
            String userName="root";
            String passWord="root";
            Connection conn = DriverManager.getConnection(url, userName, passWord);
            Statement stmt =null;
            try {
                //开启事务
                conn.setAutoCommit(false);
                //定义sql
                String sql1="update users set password=888 where id=1";
                String sql2="update users set password=666 where id=2";
                //获取执行sql的statement对象
                stmt = conn.createStatement();
                //执行sql
                int count1 = stmt.executeUpdate(sql1); //受影响的行数
                //处理结果
                System.out.println("受影响的行数:"+count1);  //受影响的行数:1
                int count2 = stmt.executeUpdate(sql2); //受影响的行数
                //处理结果
                System.out.println("受影响的行数:"+count2);  //受影响的行数:1
                //提交事务
                conn.commit();
            } catch (Exception e) {
                //回滚事务
                conn.rollback();
                e.printStackTrace();
            }
            //释放资源
            stmt.close();
            conn.close();
        }
    }
    /*
    受影响的行数:1
    受影响的行数:1
     */
    
    • 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
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46

    3.Statement

    • . Statement作用:
      • 1.执行SQL语句
    • 执行SQL语句
      • intexecuteUpdate(sql):执行DML、DDL语句
      • 返回值:(1)DML语句影响的行数(2)DDL语句执行后,执行成功也可能返回0
      • ResultSet executeQuery(sql):执行DQL语句
      • 返回值: ResultSet结果集对象

    4.ResultSet

    • ResultSet(结果集对象)作用:
      • 1.封装了DQL查询语句的结果
      • ResultSet stmt.executeQuery(sql):执行DQL语句,返回ResultSet对象
    • 获取查询结果
      • boolean next(): (1)将光标从当前位置向前移动一行(2)判断当前行是否为有效行
        • 返回值:
          • true:有效行,当前行有数据.
          • false:无效行,当前行没有数据
      • xXxgetXxx(参数):获取数据
      • xXx:数据类型;如: int getInt(参数) ; String getString(参数)
      • 参数:
        • int:列的编号,从1开始
        • String:列的名称

    案例1:

    package com.study;
    
    import java.sql.*;
    
    public class ResultSetTest {
        public static void main(String[] args) throws Exception {
            //注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            //获取连接
            String url="jdbc:mysql://localhost/jdbcone";
            String userName="root";
            String passWord="root";
            Connection conn = DriverManager.getConnection(url, userName, passWord);
            Statement stmt = null;
            ResultSet rs = null;
            try {
                //定义sql
                String sql="select * from users";
                //创建statement对象
                stmt = conn.createStatement();
                //执行sql语句
                rs = stmt.executeQuery(sql);
                //遍历rs中的数据
                while (rs.next()){
                    int id = rs.getInt("id");
                    String name = rs.getString("username");
                    String password = rs.getString("password");
                    String email= rs.getString("email");
                    System.out.println(id);
                    System.out.println(name);
                    System.out.println(password);
                    System.out.println(email);
                    System.out.println("----------------------------------------");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            //释放资源
            rs.close();
            stmt.close();
            conn.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
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44

    案例2:

    package com.study;
    
    import java.sql.*;
    import java.util.ArrayList;
    import java.util.List;
    
    public class ResultSetTestPlus {
        public static void main(String[] args) throws Exception{
            //注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            //获取连接
            String url="jdbc:mysql://localhost/jdbcone";
            String userName="root";
            String passWord="root";
            Connection conn = DriverManager.getConnection(url, userName, passWord);
            Statement stmt = null;
            ResultSet rs = null;
            //创建集合对象
           List<Account> list=new ArrayList<>();
            try {
                //定义sql
                String sql="select * from users";
                //创建statement对象
                stmt = conn.createStatement();
                //执行sql语句
                rs = stmt.executeQuery(sql);
                //遍历rs中的数据
                while (rs.next()){
                    Account account=new Account();
                    int id = rs.getInt("id");
                    String name = rs.getString("username");
                    String password = rs.getString("password");
                    String email= rs.getString("email");
                    //赋值
                    account.setId(id);
                    account.setUsername(name);
                    account.setPassword(password);
                    account.setEmail(email);
                    //存入集合
                    list.add(account);
    //                [Account{id=1, username='小马哥', password='888', email='111@qq.com'}, Account{id=2, username='小飞侠',
    //                password='666', email='222@qq.com'}, Account{id=3, username='马奎斯', password='333', email='333@qq.com'}]
    
                }
                //打印集合
                System.out.println(list);
            } catch (Exception e) {
                e.printStackTrace();
            }
            //释放资源
            rs.close();
            stmt.close();
            conn.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
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56

    5.PreparedStatement

    • PreparedStatement作用:
    • 1.预编译SQL语句并执行:预防SQL注入问题
    • SQL注入
    • SQL注入是通过操作输入来修改事先定义好的SQL语句,用以达到执行代码对服务器进行攻击的方法。
    • PreparedStatement作用:
      • 1.预编译SQL并执行SQL语句
    • 获取 PreparedStatement对象
     //SQL语句中的参数值,使用?占位符替代
    String sql = "select * from user where username = ? and password = ?";
    //通过Connection对象获取,并传入对应的sql语句
    PreparedStatement pstmt = conn.prepareStatement(sql);
    
    • 1
    • 2
    • 3
    • 4
    • 设置参数值
      • PreparedStatement对象: setXxx(参数1,参数2):给﹖赋值
      • Xxx:数据类型;如setlnt (参数1,参数2)
    • 参数:
      • 参数1:?的位置编号,从1开始
      • 参数2:?的值
    • 执行SQL
    executeUpdate(); / executeQuery()::不需要再传递sql
    
    • 1

    案例:

    package com.study;
    
    import java.sql.*;
    
    public class PreparedStatementLogin {
        public static void main(String[] args) throws Exception {
            //注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            //获取连接
            String url="jdbc:mysql://localhost/jdbcone";
            String userName="root";
            String passWord="root";
            Connection conn = DriverManager.getConnection(url, userName, passWord);
            //接收用户输入的用户名和密码
            String name="king";
            String psw="888";
            String sql="select * from users where username=? and password=?";
            //创建pstmt对象
            PreparedStatement pstmt = conn.prepareStatement(sql);
            //设置值
            pstmt.setString(1,name);
            pstmt.setString(2,psw);
    
            //执行sql语句
            ResultSet rs = pstmt.executeQuery();
            //判断是否登录成功
            if (rs.next()){
                System.out.println("登录成功!");
            }
            else {
                System.out.println("登录失败!");
            }
            rs.close();
            pstmt.close();
            conn.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
    • 34
    • 35
    • 36
    • 37
    • 38

    三、数据库连接池

    1.简介

    • 数据库连接池是个容器,负责分配、管理数据库连接(Connection)

    • 它允许应用程序重复使用一个现有的数据库连接,而不是再重新建立一个;

    • 释放空闲时间超过最大空闲时间的数据库连接来避免因为没有释放数据库连接而引起的数据库连接遗漏

    • 好处:

      • 资源重用
      • 提升系统响应速度
      • 避免数据库连接遗漏
    • 标准接口:DataSource

      • 官方(SUN)提供的数据库连接池标准接口,由第三方组织实现此接口。
      • 功能:获取连接
      • Connection getConnection)
    • 常见的数据库连接池:

      • DBCP
      • C3PO
      • Druid
    • Druid(德鲁伊)

      • Druid连接池是阿里巴巴开源的数据库连接池项目
      • 功能强大,性能优秀,是Java语言最好的数据库连接池之一

    2.使用

    • Driud使用步骤
      • 1.导入jar包,druid-1.1.1
      • 2.jar2.定义配置文件
      • 3.加载配置文件
      • 4.获取数据库连接池对象
      • 5.获取连接

    案例:

    driverClassName=com.mysql.jdbc.Driver
    url=jdbc:mysql:///users
    username=root
    password=root
    # 初始化连接数
    initialSize=5
    # 最大连接数
    maxActive=10
    # 最大等地时间
    maxWait=3000
    
    
    package com.druidTest;
    
    import com.alibaba.druid.pool.DruidDataSourceFactory;
    import javafx.scene.layout.Priority;
    
    import javax.sql.DataSource;
    import java.io.FileInputStream;
    import java.sql.Connection;
    import java.util.Properties;
    
    public class DruidTest {
        public static void main(String[] args) throws Exception {
            //导入jar包
            //定义配置文件
            //加载配置文件
            Properties prop = new Properties();
            prop.load(new FileInputStream("JDBCTest/src/druid.properties"));
            //获取连接池对象
            DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
            //获取数据库连接Connection
            Connection conn = dataSource.getConnection();
            System.out.println(conn);
    
        }
    }
    
    
    • 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
    • 34
    • 35
    • 36
    • 37
    • 38
  • 相关阅读:
    MySQL——事务和视图
    linux之应用编程回顾总结
    IntelliJ IDEA 的安装、配置与使用
    Linux——vim简介、配置方案(附带超美观的配置方案)、常用模式的基本操作
    如何绘制凸包四边形的抛面线
    【车载测试专项】 整车控制器 逻辑时序测试
    黑客专业术语认知
    数据结构大总结:有头单链表、循环链表、双线链表、栈、队列、递归、快速排序、树和哈希。
    强化学习之Dueling DQN对DQN的改进——以倒立摆环境(Inverted Pendulum)为例
    No166.精选前端面试题,享受每天的挑战和学习
  • 原文地址:https://blog.csdn.net/qq_43514330/article/details/126438307