JDBC案例student学生表的CRUD

1、数据准备

  • 数据库和数据表

    -- 创建db14数据库
    CREATE DATABASE db14;
    
    -- 使用db14数据库
    USE db14;
    
    -- 创建student表
    CREATE TABLE student(
    	sid INT PRIMARY KEY AUTO_INCREMENT,	-- 学生id
    	NAME VARCHAR(20),					-- 学生姓名
    	age INT,							-- 学生年龄
    	birthday DATE						-- 学生生日
    );
    
    -- 添加数据
    INSERT INTO student VALUES (NULL,'张三',23,'1999-09-23'),(NULL,'李四',24,'1998-08-10'),(NULL,'王五',25,'1996-06-06'),(NULL,'赵六',26,'1994-10-20');
  • 实体类

    • Student类,成员变量对应表中的列

    • 注意:所有的基本数据类型需要使用包装类,以防null值无法赋值

      import java.util.Date;
      
      public class Student {
          private Integer sid;
          private String name;
          private Integer age;
          private Date birthday;
      
          public Student() {
          }
      
          public Student(Integer sid, String name, Integer age, Date birthday) {
              this.sid = sid;
              this.name = name;
              this.age = age;
              this.birthday = birthday;
          }
      
          public Integer getSid() {
              return sid;
          }
      
          public void setSid(Integer sid) {
              this.sid = sid;
          }
      
          public String getName() {
              return name;
          }
      
          public void setName(String name) {
              this.name = name;
          }
      
          public Integer getAge() {
              return age;
          }
      
          public void setAge(Integer age) {
              this.age = age;
          }
      
          public Date getBirthday() {
              return birthday;
          }
      
          public void setBirthday(Date birthday) {
              this.birthday = birthday;
          }
      
          @Override
          public String toString() {
              return "Student{" +
                      "sid=" + sid +
                      ", name='" + name + '\'' +
                      ", age=" + age +
                      ", birthday=" + birthday +
                      '}';
          }
      }
  • 持久层定义的接口
    import Test01.domain.Student;
    
    import java.sql.SQLException;
    import java.util.ArrayList;
    
    public interface StudentDao {
        // 查询所有学生信息
        ArrayList<Student> findAll() throws SQLException;
    
        // 条件查询,根据ID获取学生信息
        Student findById(Integer id) throws SQLException;
    
        // 新增学生信息
        int insert(Student stu) throws SQLException;
    
        // 修改学生信息
        int update(Student stu) throws SQLException;
    
        // 删除学生信息
        int delete(Integer id) throws SQLException;
    }
  • 业务层定义的接口 
    import Test01.domain.Student;
    
    import java.sql.SQLException;
    import java.util.ArrayList;
    
    public interface StudentService {
        // 查询所有学生信息
        ArrayList<Student> findAll() throws SQLException;
    
        // 条件查询,根据ID获取学生信息
    
        Student findById(Integer id) throws SQLException;
    
        // 新增学生信息
        int insert(Student stu) throws SQLException;
    
        // 修改学生信息
        int update(Student stu) throws SQLException;
    
        // 删除学生信息
        int delete(Integer id) throws SQLException;
    }

    注:下面的方法重写的都是上面的接口。

需求一:查询全部

  • 持久层

    /*
         查询所有学生信息
    */
    @Override
    public ArrayList<Student> findAll() {
        ArrayList<Student> list = new ArrayList<>();
        Connection con = null;
        Statement stat = null;
        ResultSet rs = null;
        try{
            //1.注册驱动
            Class.forName("com.mysql.jdbc.Driver");
    
            //2.获取数据库连接
            con = DriverManager.getConnection("jdbc:mysql://192.168.59.129:3306/db14", "root", "itheima");
    
            //3.获取执行者对象
            stat = con.createStatement();
    
            //4.执行sql语句,并且接收返回的结果集
            String sql = "SELECT * FROM student";
            rs = stat.executeQuery(sql);
    
            //5.处理结果集
            while(rs.next()) {
                Integer sid = rs.getInt("sid");
                String name = rs.getString("name");
                Integer age = rs.getInt("age");
                Date birthday = rs.getDate("birthday");
    
                //封装Student对象
                Student stu = new Student(sid,name,age,birthday);
    
                //将student对象保存到集合中
                list.add(stu);
            }
    
        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            //6.释放资源
            if(con != null) {
                try {
                    con.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
    
            if(stat != null) {
                try {
                    stat.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
    
            if(rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        //将集合对象返回
        return list;
    }
  • 业务层

    /*
        查询所有学生信息
    */
    @Override
    public ArrayList<Student> findAll() {
        return dao.findAll();
    }
  • 控制层

    /*
        查询所有学生信息
    */
    @Test
    public void findAll() {
        ArrayList<Student> list = service.findAll();
        for(Student stu : list) {
            System.out.println(stu);
        }
    }

3.需求二:条件查询

  • 持久层

    /*
        条件查询,根据id查询学生信息
    */
    @Override
    public Student findById(Integer id) {
        Student stu = new Student();
        Connection con = null;
        Statement stat = null;
        ResultSet rs = null;
        try{
            //1.注册驱动
            Class.forName("com.mysql.jdbc.Driver");
    
            //2.获取数据库连接
            con = DriverManager.getConnection("jdbc:mysql://192.168.59.129:3306/db14", "root", "itheima");
    
            //3.获取执行者对象
            stat = con.createStatement();
    
            //4.执行sql语句,并且接收返回的结果集
            String sql = "SELECT * FROM student WHERE sid='"+id+"'";
            rs = stat.executeQuery(sql);
    
            //5.处理结果集
            while(rs.next()) {
                Integer sid = rs.getInt("sid");
                String name = rs.getString("name");
                Integer age = rs.getInt("age");
                Date birthday = rs.getDate("birthday");
    
                //封装Student对象
                stu.setSid(sid);
                stu.setName(name);
                stu.setAge(age);
                stu.setBirthday(birthday);
            }
    
        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            //6.释放资源
            if(con != null) {
                try {
                    con.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
    
            if(stat != null) {
                try {
                    stat.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
    
            if(rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        //将对象返回
        return stu;
    }
  • 业务层

    /*
        条件查询,根据id查询学生信息
    */
    @Override
    public Student findById(Integer id) {
        return dao.findById(id);
    }
  • 控制层

    /*
        条件查询,根据id查询学生信息
    */
    @Test
    public void findById() {
        Student stu = service.findById(3);
        System.out.println(stu);
    }

4.需求三:新增数据

  • 持久层

    /*
          添加学生信息
    */
    @Override
    public int insert(Student stu) {
        Connection con = null;
        Statement stat = null;
        int result = 0;
        try{
            //1.注册驱动
            Class.forName("com.mysql.jdbc.Driver");
    
            //2.获取数据库连接
            con = DriverManager.getConnection("jdbc:mysql://192.168.59.129:3306/db14", "root", "itheima");
    
            //3.获取执行者对象
            stat = con.createStatement();
    
            //4.执行sql语句,并且接收返回的结果集
            Date d = stu.getBirthday();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String birthday = sdf.format(d);
            String sql = "INSERT INTO student VALUES ('"+stu.getSid()+"','"+stu.getName()+"','"+stu.getAge()+"','"+birthday+"')";
            result = stat.executeUpdate(sql);
    
        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            //6.释放资源
            if(con != null) {
                try {
                    con.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
    
            if(stat != null) {
                try {
                    stat.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        //将结果返回
        return result;
    }
  • 业务层

    /*
        新增学生信息
    */
    @Override
    public int insert(Student stu) {
        return dao.insert(stu);
    }
  • 控制层

    /*
      	新增学生信息
    */
    @Test
    public void insert() {
        Student stu = new Student(5,"周七",27,new Date());
        int result = service.insert(stu);
        if(result != 0) {
            System.out.println("新增成功");
        }else {
            System.out.println("新增失败");
        }
    }

 

5.需求四:修改数据

  • 持久层

    /*
        修改学生信息
    */
    @Override
    public int update(Student stu) {
        Connection con = null;
        Statement stat = null;
        int result = 0;
        try{
            //1.注册驱动
            Class.forName("com.mysql.jdbc.Driver");
    
            //2.获取数据库连接
            con = DriverManager.getConnection("jdbc:mysql://192.168.59.129:3306/db14", "root", "itheima");
    
            //3.获取执行者对象
            stat = con.createStatement();
    
            //4.执行sql语句,并且接收返回的结果集
            Date d = stu.getBirthday();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String birthday = sdf.format(d);
            String sql = "UPDATE student SET sid='"+stu.getSid()+"',name='"+stu.getName()+"',age='"+stu.getAge()+"',birthday='"+birthday+"' WHERE sid='"+stu.getSid()+"'";
            result = stat.executeUpdate(sql);
    
        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            //6.释放资源
            if(con != null) {
                try {
                    con.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
    
            if(stat != null) {
                try {
                    stat.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        //将结果返回
        return result;
    }
  • 业务层

    /*
        修改学生信息
    */
    @Override
    public int update(Student stu) {
        return dao.update(stu);
    }
  • 控制层

    /*
        修改学生信息
    */
    @Test
    public void update() {
        Student stu = service.findById(5);
        stu.setName("周七七");
    
        int result = service.update(stu);
        if(result != 0) {
            System.out.println("修改成功");
        }else {
            System.out.println("修改失败");
        }
    }

6.需求五:删除数据

  • 持久层

    /*
        删除学生信息
    */
    @Override
    public int delete(Integer id) {
        Connection con = null;
        Statement stat = null;
        int result = 0;
        try{
            //1.注册驱动
            Class.forName("com.mysql.jdbc.Driver");
    
            //2.获取数据库连接
            con = DriverManager.getConnection("jdbc:mysql://192.168.59.129:3306/db14", "root", "itheima");
    
            //3.获取执行者对象
            stat = con.createStatement();
    
            //4.执行sql语句,并且接收返回的结果集
            String sql = "DELETE FROM student WHERE sid='"+id+"'";
            result = stat.executeUpdate(sql);
    
        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            //6.释放资源
            if(con != null) {
                try {
                    con.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
    
            if(stat != null) {
                try {
                    stat.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        //将结果返回
        return result;
    }
  • 业务层

    /*
        删除学生信息
    */
    @Override
    public int delete(Integer id) {
        return dao.delete(id);
    }
  • 控制层

    /*
        删除学生信息
    */
    @Test
    public void delete() {
        int result = service.delete(5);
    
        if(result != 0) {
            System.out.println("删除成功");
        }else {
            System.out.println("删除失败");
        }
    }

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

悠然予夏

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值