细致刨析JDBC ① 基础篇

“加油” 我已经说腻了,下次我要说:”祝你拥有随时停留和休息的底气“

                                                                                                        —— 24.9.6

一、JDBC概述

1.JDBC的概念

JDBC:Java Database Connectivity,意为Java数据库连接

JDBC是Java提供的一组独立于任何数据库管理系统的API。

Java提供接口规范,由各个数据库厂商提供接口的实现,厂商提供的实现类封装成jar文件,也就是我们俗称的数据库驱动jar包。


2.JDBC的核心组成

① 接口规范:

        为了项目代码的可移植性,可维护性,SUN公司从最初就制定了Java程序连接各种数据库的统一接口规0范。这样的话,不管是连接哪一种DBMS软件,Java代码可以保持一致性。
        接口存储在java.sql和javax.sql包下。

② 实现规范:

        因为各个数据库厂商的DBMS软件各有不同,那么各自的内部如何通过SQL实现增、删、改、查等操作管理数据,只有这个数据库厂商自己更清楚,因此把接口规范的实现交给各个数据库厂商自己实现。
        厂商将实现内容和过程封装成iar文件,我们程序员只需要将jar文件引入到项目中集成即可,就可以开发调用实现过程操作数据库了。

二、JDBC快速入门

1.JDBC搭建步骤

① 准备数据库

create database JavaWebJDBC;

use JavaWebJDBC;

create table t_emp
(
    emp_id     int auto_increment comment '员工编号' primary key,
    emp_name   varchar(100)  not null comment '员工姓名',
    emp_salary double(10, 5) not null comment '员工薪资',
    emp_age    int           not null comment '员工年龄'
);

insert into t_emp (emp_name,emp_salary,emp_age)
values  ('andy', 777.77, 32),
        ('大风哥', 666.66, 41),
        ('康师傅',111, 23),
        ('Gavin',123, 26),
        ('小鱼儿', 123, 28);
        

② 官网下载数据库连接驱动jar包。

下载链接:https://downloads.mysql.com/archives/c-j/

③ 创建Java项目,在项目下创建lib文件夹,将下载的驱动jar包复制到文件夹里。

④ 选中lib文件夹右键 ——> Add as Library,与项目集成。

⑤ 编写代码

import com.mysql.cj.jdbc.Driver;

import java.sql.*;

public class Demo1_JdbcQuick {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //1.注册驱动
        // 方式1
        // Class.forName("com.mysql.cj.jdbc.Driver");
        // 方式2
        DriverManager.registerDriver(new Driver());

        //2.获取数据库连接对象
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/javawebjdbc", "root", "954926928lcl");

        //3.创建Statement发送执行sql语句的对象
        PreparedStatement preparedStatement = connection.prepareStatement("select emp_id,emp_name,emp_salary,emp_age from t_emp");

        //4.编写SQL语句并执行,获取结果集
        ResultSet resultSet = preparedStatement.executeQuery();

        //5.处理结果:遍历resultSet结果集
        while (resultSet.next()) { // 下一行的遍历
            // 用列名获取
            int empId = resultSet.getInt("emp_id");
            String empName = resultSet.getString("emp_name");
            String empSalary = resultSet.getString("emp_salary");
            int empAge = resultSet.getInt("emp_age");
            System.out.println(empId + "\t" + empName + "\t" + empSalary + "\t" + empAge);
        }

        //6.释放资源(先开后关原则)
        resultSet.close();
        preparedStatement.close();
        connection.close();

    }
}

三、核心API理解

1.注册驱动

Class.forName("com.mysql.cj.jdbc.Driver");

        在Java中,当使用 JDBC(Java Database Connectivity)连接数据库时,需要加载数据库特定的驱动程序,以便与数据库进行通信。加载驱动程序的目的是为了注册驱动程序,使得JDBC API能够识别并与特定的数据库进行交互。

        jdk的Driver源码

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.mysql.cj.jdbc;

import java.sql.DriverManager;
import java.sql.SQLException;

public class Driver extends NonRegisteringDriver implements java.sql.Driver {
    public Driver() throws SQLException {
    }

    static {
        try {
            DriverManager.registerDriver(new Driver());
        } catch (SQLException var1) {
            throw new RuntimeException("Can't register driver!");
        }
    }
}

        从JDK6开始,不再需要显式地调用 class.forName()(两种方式都不需要写,Java可以自动注册驱动来加载JDBC 驱动程序,只要在类路径中集成了对应的jar文件,会自动在初始化时注册驱动程序。

2.Connection

 Connection接口是JDBC API的重要接口,用于建立与数据库的通信通道。换而言之,Connection对象不为空,则代表一次数据库连接。

① 在建立连接时,需要指定数据库URL、用户名、密码参数。

        URL:jdbc:mysql://localhost:3306/javawebjdbc     

                jdbc:mysql://IP地址:端口号/数据库名称?参数键值对1&参数键值对2

② Connection 接口还负责管理事务,Connection 接口提供了 commit 和 rollback方法,用于提交事务和回滚事务。

③ 可以创建 Statement 对象,用于执行 SQL 语句并与数据库进行交互。

④ 在使用JDBC技术时,必须要先获取Connection对象,在使用完毕后,要释放资源,避免资源占用浪费及泄漏。

3.Statement     

        ① Statement接口用于执行 SQL 语句并与数据库进行交互。它是 JDBC API 中的一个重要接口。通过 Statement 对象,可以向数据库发送 SQL 语句并获取执行结果。

        ② 结果可以是一个或多个结果。

                  增删改:受影响行数单个结果。

                  查询:单行单列、多行多列、单行多列等结果。

        ③ 但是`Statement` 接口在执行SQL语句时,会产生 SQL注入攻击问题:

                当使用 Statement 执行动态构建的 SQL 查询时,往往需要将查询条件与 SQL 语句拼接在一起,直接将参数和SQL语句一并生成,让SQL的查询条件始终为true得到结果。

package JDBC_Base;

import java.sql.*;
import java.util.Scanner;

public class Demo2_InjectionInjure {
    public static void main(String[] args) throws SQLException {
        // 1.省略注册驱动

        // 2.获取数据库连接对象
        Connection con = DriverManager.getConnection("jdbc:mysql:///javawebjdbc","root","954926928lcl");

        // 3.获取执行SQL语句对象
        Statement stmt = con.createStatement();

        // 加入操作:请输入员工姓名
        System.out.println("请输入员工姓名");
        Scanner sc = new Scanner(System.in);
        String name = sc.nextLine();

        // 4.编写SQL语句,并执行,接受返回的结果
        String sql = "select emp_id,emp_name,emp_age,emp_salary from t_emp where emp_name = '"+name+"'";
        ResultSet rs = stmt.executeQuery(sql);

        //5.处理结果:遍历resultSet结果集
        while (rs.next()) { // 下一行的遍历
            // 用列名获取
            int empId = rs.getInt("emp_id");
            String empName = rs.getString("emp_name");
            String empSalary = rs.getString("emp_salary");
            int empAge = rs.getInt("emp_age");
            System.out.println(empId + "\t" + empName + "\t" + empSalary + "\t" + empAge);
        }

        // 6.释放资源 先开后关
        rs.close();
        stmt.close();
        con.close();
    }
}

4.PreparedStatement 

        PreparedStatement 是 Statement 接囗的子接口,用于执行 预编译的 SQL 查询,作用如下:

        ① 预编译SQL语句:在创建Preparedstatement时,就会预编译SQL语句,也就是SQL语句已经固定。
        ② 防止SQL注入: Preparedstatement 支持参数化査询,将数据作为参数传递到SQL语句中,采用 ? 占位符的方式,将传入的参数用一对单引号包裹起来",无论传递什么都作为值。有效防止传入关键字或值导致SQL注入问题。
        ③ 性能提升:Preparedstatement是预编译SQL语句,同一SQL语句多次执行的情况下,可以复用,不必每次重新编译和解析。
        ④ 后续的学习我们都是基于Preparedstatement进行实现,更安全、效率更高!

package JDBC_Base;

import java.sql.*;
import java.util.Scanner;

public class Demo3Prepared {
     public static void main(String[] args) throws SQLException {
          // 1.省略注册驱动

         // 2.获取数据库连接对象
         Connection con = DriverManager.getConnection("jdbc:mysql:///javawebjdbc","root","954926928lcl");

         // 3.获取执行SQL语句对象
         PreparedStatement preparedStatement = con.prepareStatement("select emp_id,emp_name,emp_age,emp_salary from t_emp where emp_name = ?");

         // 加入操作:请输入员工姓名
         System.out.println("请输入员工姓名");
         Scanner sc = new Scanner(System.in);
         String name = sc.nextLine();

         // 4.慰?占位符赋值,并执行SQL语句,并接受返回的结果
         preparedStatement.setString(1,name);
         ResultSet rs = preparedStatement.executeQuery();

         //5.处理结果:遍历resultSet结果集
         while (rs.next()) { // 下一行的遍历
             // 用列名获取
             int empId = rs.getInt("emp_id");
             String empName = rs.getString("emp_name");
             String empSalary = rs.getString("emp_salary");
             int empAge = rs.getInt("emp_age");
             System.out.println(empId + "\t" + empName + "\t" + empSalary + "\t" + empAge);
         }

         // 6.释放资源 先开后关
         rs.close();
         preparedStatement.close();
         con.close();
     }
}

之所以prepareStatement可以预防SQL注入问题,是因为多出一个转义操作,会将引号转义作为一个普通字符,所以prepareStatement可以预防SQL注入问题

5.ResultSet

        ResultSet是 JDBC API 中的一个接口,用于表示从数据库中执行查询语句所返回的结果集。它提供了一种用于遍历和访问查询结果的方式。

        遍历结果:ResultSet可以使用 next() 方法将游标移动到结果集的下一行,逐行遍历数据库查询的结果,返回值为boolean类型,true代表有下一行结果,false则代表没有

        获取单列结果:可以通过getXxx的方法获取单列的数据,该方法为重载方法,支持索引和列名进行获取。

四、基于Preparedment实现CRUD

1.查询单行单列

import org.junit.Test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class Demo4Operation {
    @Test
    public void testQuerySingleRowAndCow() throws Exception {
        // 1.注册驱动 可以省略

        // 2.获取链接
        Connection con = DriverManager.getConnection("jdbc:mysql:///javawebjdbc","root","954926928lcl");

        // 3.预编译SQL语句得到P热爱怕热的Statement对象
        PreparedStatement preparedStatement = con.prepareStatement("select count(*) as count from t_emp");

        // 4.执行SQL语句,获取结果
        ResultSet resultSet = preparedStatement.executeQuery();

        // 5.处理结果
        while (resultSet.next()) {
            int count = resultSet.getInt("count");
            System.out.println(count);
        }

        // 6.释放资源
        resultSet.close();
        preparedStatement.close();
        con.close();
    }
}

2.查询单行多列

import org.junit.Test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class Demo4Operation {
    @Test
    public void testQuerySingleRow() throws Exception {
        // 1.注册驱动 可以省略

        // 2.获取链接
        Connection con = DriverManager.getConnection("jdbc:mysql:///javawebjdbc","root","954926928lcl");

        // 3.预编译SQL语句得到P热爱怕热的Statement对象
        PreparedStatement pS = con.prepareStatement("select emp_id,emp_name,emp_salary,emp_age from t_emp where emp_id = ?");

        // 4.为占位符赋值
        pS.setInt(1,5);

        // 5.执行SQL语句,获取结果
        ResultSet resultSet = pS.executeQuery();

        // 6.处理结果
        while (resultSet.next()) {
            int emp_id = resultSet.getInt("emp_id");
            String emp_name = resultSet.getString("emp_name");
            int emp_age = resultSet.getInt("emp_age");
            double emp_salary = resultSet.getDouble("emp_salary");
            System.out.println(emp_id+"\t"+emp_name+"\t"+emp_age+"\t"+emp_salary);
        }

        // 7.释放资源
        resultSet.close();
        pS.close();
        con.close();

    }
}

3.查询多行多列

import org.junit.Test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class Demo4Operation {
    @Test
    public void testQueryMoreCow() throws Exception {
        // 1.注册驱动 可以省略

        // 2.获取链接
        Connection con = DriverManager.getConnection("jdbc:mysql:///javawebjdbc","root","954926928lcl");

        // 3.预编译SQL语句得到P热爱怕热的Statement对象
        PreparedStatement pS = con.prepareStatement("select emp_id,emp_name,emp_salary,emp_age from t_emp where emp_age > ?");

        // 4.为占位符赋值,执行SQL语句,接受结果
        // 加入操作:请输入员工年龄
        System.out.println("请输入员工最低年龄");
        Scanner sc = new Scanner(System.in);
        int age = sc.nextInt();

        // 5.执行SQL语句,获取结果
        pS.setInt(1,age);
        ResultSet resultSet = pS.executeQuery();

        // 6.处理及过
        while (resultSet.next()) {
            int emp_id = resultSet.getInt("emp_id");
            String emp_name = resultSet.getString("emp_name");
            double emp_salary = resultSet.getDouble("emp_salary");
            int emp_age = resultSet.getInt("emp_age");

            System.out.println(emp_id+"\t"+emp_name+"\t"+emp_salary+"\t"+emp_age);
        }

        // 7.释放资源
        resultSet.close();
        pS.close();
        con.close();
    }
}

4.实现CRUD修改

import org.junit.Test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class Demo4Operation {
    @Test
    public void testUpdate() throws Exception {
        // 1.注册驱动 可以省略

        // 2.获取链接
        Connection con = DriverManager.getConnection("jdbc:mysql:///javawebjdbc","root","954926928lcl");

        // 3.预编译SQL语句得到PrepareStatement对象
        PreparedStatement pS = con.prepareStatement("update t_emp set emp_salary = ? where emp_id = ?");

        // 4.为占位符赋值
        pS.setDouble(1,500);
        pS.setInt(2,5);

        int res = pS.executeUpdate();

        if (res > 0) {
            System.out.println("成功修改");
        }else{
            System.out.println("修改失败");
        }

        pS.close();
        con.close();
    }
}

5.实现CRUD新增

import org.junit.Test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class Demo4Operation {
    @Test
    public void testInsert() throws Exception {
        // 1.注册驱动 可以省略

        // 2.获取链接
        Connection con = DriverManager.getConnection("jdbc:mysql:///javawebjdbc","root","954926928lcl");

        // 3.预编译SQL语句得到PrepareStatement对象
        PreparedStatement pS = con.prepareStatement("insert into t_emp(emp_name,emp_salary,emp_age) values(?,?,?)");

        // 4.为占位符赋值
        pS.setString(1,"rose");
        pS.setDouble(2,563.65);
        pS.setInt(3,35);

        int res = pS.executeUpdate();

        if (res > 0) {
            System.out.println("成功新增");
        }else{
            System.out.println("新增失败");
        }

        pS.close();
        con.close();
    }
}

6.实现CRUD删除

import org.junit.Test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class Demo4Operation {
    @Test
    public void testDelete() throws Exception {
        // 1.注册驱动 可以省略

        // 2.获取链接
        Connection con = DriverManager.getConnection("jdbc:mysql:///javawebjdbc","root","954926928lcl");

        // 3.预编译SQL语句得到PrepareStatement对象
        PreparedStatement pS = con.prepareStatement("delete from t_emp where emp_id = ?");

        // 4.为占位符赋值
        pS.setInt(1,6);

        int res = pS.executeUpdate();

        if (res > 0) {
            System.out.println("成功删除");
        }else{
            System.out.println("删除失败");
        }

        pS.close();
        con.close();
    }
}

五、常见问题

1.资源的管理

2.SQL语句问题

3.SQL语句未设置参数问题

4.用户名或密码错误问题

5.通信异常

  • 25
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值