JDBC---把查询的结果封装到相应的实体上(实体类entity) 把对每一张表的操作封装到相应的类上(操作类Dao) 抽取一个dao的公共父类 可变长度的参数

目录

1.回顾

2.把查询的结果封装到相应的实体上(实体类)

 3.对每张表的操作封装到相应的类上(操作类)--对应的Dao类

4.使用try-catch-finally来处理异常

5.抽取一个dao的公共父类

5.1.为什么要抽取父类

5.2.为添加删除修改抽取公共方法

6.可变长度的参数

7.总结


1.回顾

1. jdbc--查询功能。
2. sql注入的安全问题解决方案.
   (1)加载驱动:Class.forName("mysql驱动名称");
   (2)获取连接对象:Connection conn=DriverManager.getConnection(url,u,pass);
   (3)获取执行sql语句的对象:
      PreparedStatement ps=conn.prepareStatement(sql);//预编译sql
   (4)为占位符赋值
      ps.setXXX(index,value); //index:表示占位符的索引。value:表示占位符的值
   (5)执行sql语句。
       ps.executeUpdate();//执行增删改的sql
       ResultSet rs=ps.executeQuery();//执行查询的sql
   (6)遍历ResultSet中的内容.
       while(rs.next()){ //判断指针是否可以移动,如果可以移动则移动到下一行记录
            rs.getXXX("列名"); //获取当前行的指定列的值。
       }

2.把查询的结果封装到相应的实体上(实体类)

 注意: 我们这里把查询的结果直接输出到控制台了,而实际开发中,我们需要把查询的结果展示到浏览器网页上,效果如下

 如何把查询的结果封装起来。

java的一个类对应数据库的一张表。
java类中的属性对应数据库中的列名。
java的一个对象对应数据库中一条记录。
java的集合List<类名>对应表中多条记录。

这个类专业叫法------------------->实体类。建议大家把实体类放在entity包。

@Test
    public void testSelect() throws Exception {
        Class.forName("com.mysql.cj.jdbc.Driver");
        String url = "jdbc:mysql://localhost:3306/mydb?serverTimezone=Asia/Shanghai";
        String user = "root";
        String password = "root";
        Connection connection = DriverManager.getConnection(url, user, password);
        String sql = "select * from tb_dept"; //因为这里没有占位符 所以可以不用为占位符赋值
        PreparedStatement ps= connection.prepareStatement(sql);
        ResultSet rs = ps.executeQuery();

        List<Dept> list = new ArrayList<>(); //集合存放数据库表中所有记录
        while (rs.next()){
            int id = rs.getInt("id");
            String name = rs.getString("name");
            //创建一个实体类对象 存储表中的一条记录。
            Dept d = new Dept();
            d.setId(id);
            d.setName(name);

            list.add(d);
        }
        System.out.println(list); //正常再开发中应该把该对象list返回给前端。
 @Test
    public void testSelectOne() throws Exception{
        Class.forName("com.mysql.cj.jdbc.Driver");
        String url = "jdbc:mysql://localhost:3306/mydb?serverTimezone=Asia/Shanghai";
        String user = "root";
        String password = "root";
        Connection connection = DriverManager.getConnection(url, user, password);
        String sql = "select * from tb_dept where id=?"; //这里根据id查询的结果一定是一条记录。因为id是主键。
        PreparedStatement ps= connection.prepareStatement(sql);
        ps.setInt(1,9);    //1表示第一个占位符 9表示占位符的值

        ResultSet rs = ps.executeQuery();
        Dept d=null;//声明部门实体类对象。
        while (rs.next()){
            d =  new Dept(); //因为进入该语句表示从数据库中查询到相应的记录了。
            int id = rs.getInt("id");
            String name = rs.getString("name");
            d.setId(id);
            d.setName(name);
        }

        System.out.println(d); //以后可以把d返回给前端调用者

    }

如果查询的结果为多条记录使用ArrayList存储多条记录而每一条还是用实体类对象。

如果查询的结果确定为一条,直接使用实体类。

 3.对每张表的操作封装到相应的类上(操作类)--对应的Dao类

思考: 我们如果把所有表的操作都写在一个类中,那么该类的代码会变得越来越臃肿,对应后期维护也不方便,真正再企业开发时我们会对每张表得操作都封装一个对应得操作类。

后缀都是Dao -----Data access Object 数据访问对象层

tb_dept  对应一个操作类 DeptDao该操作类中包含所有对tb_dept表得增删改查得操作。
tb_student 对应一个操作 StudentDao

习惯把这些对表得操作类放入到dao包。

package com.ykq.dao;

import com.ykq.entity.Dept;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;


 //专门对tb_dept表操作得类。

public class DeptDao {

    private String driverName="com.mysql.cj.jdbc.Driver";
    private String url="jdbc:mysql://localhost:3306/mydb?serverTimezone=Asia/Shanghai";
    private String user="root";
    private String password="root";

    //根据id查询部门信息
    public Dept findOne(int id) throws Exception{
        Class.forName(driverName);
        Connection connection = DriverManager.getConnection(url, user, password);
        String sql = "select * from tb_dept where id=?"; //这里根据id查询的结果一定是一条记录。因为id是主键。
        PreparedStatement ps= connection.prepareStatement(sql);
        ps.setInt(1,id);

        ResultSet rs = ps.executeQuery();
        Dept d=null;//声明部门实体类对象。
        while (rs.next()){
            d =  new Dept(); //因为进入该语句表示从数据库中查询到相应的记录了。
            d.setId(rs.getInt("id"));
            d.setName(rs.getString("name"));
        }
        return d;
    }

    //查询操作--查询所有
    public List<Dept> findAll() throws Exception{
        List<Dept> list=new ArrayList<>();
        Class.forName(driverName);
        Connection connection = DriverManager.getConnection(url,user,password);
        String sql= "select * from tb_dept";
        PreparedStatement ps=connection.prepareStatement(sql);
        ResultSet rs = ps.executeQuery();

        while (rs.next()){
            //创建一个实体类对象 存储表中的一条记录。
            Dept d = new Dept();
            d.setId(rs.getInt("id"));
            d.setName(rs.getString("name"));
            list.add(d);
        }
        return list;
    }

    //增加操作--要不要传递参数
    public void insertDept(Dept dept) throws Exception{ //把前端输入得部门信息封装到相应得实体类。
        Class.forName(driverName);
        Connection connection = DriverManager.getConnection(url,user,password);
        String sql = "insert into tb_dept values(null,?)";
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setObject(1,dept.getName());
        ps.executeUpdate();
    }

    //删除操作--根据id删除
    public void delete(int id)throws Exception{
        Class.forName(driverName);
        Connection connection = DriverManager.getConnection(url,user,password);
        String sql = "delete from tb_dept where id=?";
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setObject(1,id);
        ps.executeUpdate();
    }
    //修改操作 --根据id修改
    public void update(Dept dept) throws Exception{
        Class.forName(driverName);
        Connection connection = DriverManager.getConnection(url,user,password);
        String sql = "update tb_dept set name=? where id=?";
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setObject(1,dept.getName());
        ps.setObject(2,dept.getId());
        ps.executeUpdate();
    }
}

4.使用try-catch-finally来处理异常

操作类:

package com.wzh.Dao;

import com.wzh.entity.Student;
import org.junit.Test;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author : wzh
 * @date 2022/5/6 19:01:21
 */
//专门Student表的操作类
public class StudentDao {
    private String driverName = "com.mysql.cj.jdbc.Driver";
    private String url = "jdbc:mysql://localhost:3306/mycc?serverTimezone=Asia/Shanghai";
    private String user = "root";
    private String password = "123456";
    Connection connection = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    //增
    public void insert(Student student){
        try {
            Class.forName(driverName);
            connection = DriverManager.getConnection(url,user,password);
            String sql = "insert into student values(null,?,?,?)";
            ps = connection.prepareStatement(sql);
            ps.setObject(1,student.getName());
            ps.setObject(2,student.getAge());
            ps.setObject(3,student.getAddress());
            ps.executeUpdate();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            try {
                if(ps!=null){
                    ps.close();
                }
                if(connection!=null){
                    connection.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
    //删
    public void delete(int id){
        try {
            Class.forName(driverName);
            connection = DriverManager.getConnection(url,user,password);
            String sql = "delete from student where id=?";
            ps = connection.prepareStatement(sql);
            ps.setObject(1,id);
            ps.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if(ps!=null){
                    ps.close();
                }
                if(connection!=null){
                    connection.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
    @Test   //改
    public void update(Student student){
        try {
            Class.forName(driverName);
            connection = DriverManager.getConnection(url,user,password);
            String sql = "update student set name=?,age=?,address=? where id=?";
            ps = connection.prepareStatement(sql);
            ps.setObject(1,student.getName());
            ps.setObject(2,student.getAge());
            ps.setObject(3,student.getAddress());
            ps.setObject(4,student.getId());
            ps.executeUpdate();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            try {
                if(ps!=null){
                    ps.close();
                }
                if(connection!=null){
                    connection.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
    //查多条记录
    public List<Student> selectAll(){
        List<Student> list = new ArrayList<>();
        try {
            Class.forName(driverName);
            connection = DriverManager.getConnection(url,user,password);
            String sql = "select * from student";
            ps = connection.prepareStatement(sql);
            rs = ps.executeQuery();
            while(rs.next()){
               Student s = new Student();
               s.setId(rs.getInt("id"));
               s.setName(rs.getString("name"));
               s.setAge(rs.getInt("age"));
               s.setAddress(rs.getString("address"));
               list.add(s);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            try {
                if(rs!=null){
                    rs.close();
                }
                if(ps!=null){
                    ps.close();
                }
                if(connection!=null){
                    connection.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return list;
    }
    //查一条记录
    public Student selectOne(int id){
        Student student = null;
        try {
            Class.forName(driverName);
            connection = DriverManager.getConnection(url,user,password);
            String sql = "select * from student where id=?";
            ps = connection.prepareStatement(sql);
            ps.setObject(1,id);
            rs = ps.executeQuery();
            student = null;
            while(rs.next()){
                student = new Student();
                student.setId(rs.getInt("id"));
                student.setName(rs.getString("name"));
                student.setAge(rs.getInt("age"));
                student.setAddress(rs.getString("address"));
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            try {
                if(rs!=null){
                    rs.close();
                }
                if(ps!=null){
                    ps.close();
                }
                if(connection!=null){
                    connection.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return student;
    }
}

实体类:

package com.wzh.entity;

/**
 * @author : wzh
 * @date 2022/5/6 19:00:08
 */
public class Student {
    private int id;
    private String name;
    private int age;
    private String address;

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", address='" + address + '\'' +
                '}';
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

测试类:

package com.wzh;

import com.wzh.Dao.StudentDao;
import com.wzh.entity.Student;
import org.junit.Test;

import java.util.List;

/**
 * @author : wzh
 * @date 2022/5/6 19:09:27
 */
public class TestStudentDao {
    StudentDao studentDao = new StudentDao();
    @Test   //测试增
    public void testInsert(){
        Student student = new Student();
        student.setName("孙七");
        student.setAge(18);
        student.setAddress("郑州");
        studentDao.insert(student);
    }
    @Test //测试删
    public void testDelete(){
        studentDao.delete(2);
    }
    @Test //测试改
    public void testUpdate(){
        Student student = new Student();
        student.setName("王八");
        student.setAge(18);
        student.setAddress("郑州");
        student.setId(16);
        studentDao.update(student);
    }
    @Test //测试查所有
    public void testSelectAll(){
        List<Student> students = studentDao.selectAll();
        for(Student s : students){
            System.out.println(s.getId()+"\t"+s.getName()+"\t"+s.getAge()+"\t"+s.getAddress());
        }
    }
    @Test   //查一条记录
    public void testSelectOne(){
        Student s = studentDao.selectOne(15);
        System.out.println(s.getId()+"\t"+s.getName()+"\t"+s.getAge()+"\t"+s.getAddress());
    }
}

5.抽取一个dao的公共父类

5.1.为什么要抽取父类

因为我们对每一张表都封装了一个操作类,那么再数据库中有很多表,那么我们就会有很多操作类,这些操作类都有一些公共的代码,为了减少代码的冗余,我们就抽取了一个父类。

package com.ykq.dao;

import java.sql.*;

/**
 * @program: jdbc03
 * @description:
 * @create: 2022-05-07 
 * 该类就是一个父类。该类中包含子类中一些公共的属性和方法。
 **/
public class BaseDao {
    //公共属性
    private String driverName = "com.mysql.cj.jdbc.Driver";
    private String url = "jdbc:mysql://localhost:3306/mydb?serverTimezone=Asia/Shanghai";
    private String user = "root";
    private String password = "root";
    protected PreparedStatement ps = null;  //protected同包以及不同包下的子类都可以使用该修饰符修饰的成员
    protected Connection connection = null;
    protected ResultSet rs = null;

    //获取连接对象。
    public Connection getConn() throws Exception { //这里要处理异常还是抛出异常。
        Class.forName(driverName);
        connection = DriverManager.getConnection(url, user, password);
        return connection;
    }
    //关闭资源的方法。
    public void closeAll(){
        try {
            if(rs!=null){ //判断是否为空
                rs.close();
            }
            if(ps!=null){
                ps.close();
            }
            if(connection!=null){
                connection.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

5.2.为添加删除修改抽取公共方法

父类的代码:

//抽取一个增删改 公共方法
    public void edit(String sql,Object... params){
        try {
            connection = getConn();
            //意外
            ps = connection.prepareStatement(sql);
            //为占位符赋值
            for(int i=0;i<params.length;i++){
                ps.setObject(i+1, params[i]);
            }
            ps.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeAll();
        }
    }

子类的代码 :

package com.wzh.dao;

import com.wzh.entity.Emp;

import java.util.ArrayList;
import java.util.List;

/**
 * @author : wzh
 * @date 2022/5/7 23:23:06
 */
public class EmpDao extends BaseDao{
    //增加操作
    public void insert(Emp e){
        String sql = "insert into tb_emp values(null,?,?,?,?,?,?,?)";
        edit(sql,e.getName(),e.getAge(),e.getJob(),e.getSalary(),e.getEntrydate(),e.getManagerid(),e.getDeptId());
    }
    //删除操作
    public void delete(int id){
        String sql = "delete from tb_emp where id=?";
        edit(sql,id);
    }
    //修改操作
    public void update(Emp e){
        String sql = "update tb_emp set name=?,age=?,job=?,salary=?,entrydate=?,managerid=?,dept_id=? where id=?";
        edit(sql,e.getName(),e.getAge(),e.getJob(),e.getSalary(),e.getEntrydate(),e.getManagerid(),e.getDeptId(),e.getId());//传递的参数顺序一定要和占位符的顺序一致。
    }
    //查找全部
    public List<Emp> selectAll(){
        List<Emp> list = new ArrayList<>();
        try {
            conn = getConn();
            String sql = "select id,name,age,job,salary,entrydate,managerid,dept_id from tb_emp";
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while(rs.next()){
                Emp e = new Emp();
                e.setId(rs.getInt("id"));
                e.setName(rs.getString("name"));
                e.setAge(rs.getInt("age"));
                e.setSalary(rs.getInt("salary"));
                e.setEntrydate(rs.getDate("entrydate"));
                e.setManagerid(rs.getInt("managerid"));
                e.setDeptId(rs.getInt("dept_id"));
                list.add(e);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeAll();
        }
        return list;
    }
    //根据id查找一条记录
    public Emp selectOne(int id){
        Emp e = null;
        try {
            conn = getConn();
            String sql = "select id,name,age,job,salary,entrydate,managerid,dept_id from tb_emp where id=?";
            ps = conn.prepareStatement(sql);
            ps.setObject(1,id);
            rs = ps.executeQuery();
            e = null;
            while(rs.next()){
                e = new Emp();
                e.setId(rs.getInt("id"));
                e.setName(rs.getString("name"));
                e.setAge(rs.getInt("age"));
                e.setSalary(rs.getInt("salary"));
                e.setEntrydate(rs.getDate("entrydate"));
                e.setManagerid(rs.getInt("managerid"));
                e.setDeptId(rs.getInt("dept_id"));
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        } finally {
            closeAll();
        }
        return e;
    }
}

 测试类:

package com.wzh;

import com.wzh.dao.EmpDao;
import com.wzh.entity.Emp;
import org.hamcrest.internal.SelfDescribingValueIterator;
import org.junit.Test;
import sun.java2d.pipe.SpanShapeRenderer;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author : wzh
 * @date 2022/5/7 23:27:18
 */
public class TestEmpDao{
    EmpDao empDao = new EmpDao();
    @Test
    public void testInsert(){
        Emp e = new Emp();
        e.setName("赵六");
        e.setAge(18);
        e.setJob("销售");
        e.setSalary(8000);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = sdf.parse("2000-10-02");
        } catch (ParseException parseException) {
            parseException.printStackTrace();
        }
        e.setEntrydate(date);
        e.setManagerid(1);
        e.setDeptId(5);
        empDao.insert(e);
    }
    @Test
    public void testDelete(){
        empDao.delete(18);
    }
    @Test
    public void testUpdate(){
        Emp e = new Emp();
        e.setId(19);
        e.setName("孙旺");
        e.setAge(25);
        e.setJob("开发");
        e.setSalary(9000);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = sdf.parse("2000-10-10");
        } catch (ParseException parseException) {
            parseException.printStackTrace();
        }
        e.setEntrydate(date);
        e.setManagerid(10);
        e.setDeptId(4);
        empDao.update(e);
    }
    @Test
    public void testSelectAll(){
        List<Emp> emps = empDao.selectAll();
        for(Emp e : emps){
            System.out.println(e.getId()+"\t"+e.getName()+"\t"+e.getAge()+"\t"+e.getJob()+"\t"+e.getSalary()+"\t"+e.getEntrydate()+"\t"+e.getManagerid()+"\t"+e.getDeptId());
        }
    }
    @Test
    public void testSelectOne(){
        Emp e= empDao.selectOne(19);
        System.out.println(e.getId()+"\t"+e.getName()+"\t"+e.getAge()+"\t"+e.getJob()+"\t"+e.getSalary()+"\t"+e.getEntrydate()+"\t"+e.getManagerid()+"\t"+e.getDeptId());

    }
}

6.可变长度的参数

Object ... a : ...表示可变长度的参数

public class Test02 {
    public static void main(String[] args) {
//        fun("hello");
//        fun(23);
//        fun(15.6);

        fun02(); //
        fun02("hello");
        fun02("hello",153);
        fun02("hello",153,25.6);
    }
    //...可变参可以理解为把实参封装到数组中
    public static void fun02(Object ... a){ //...表示可变长度的参数
        for(int i=0;i<a.length;i++){
            System.out.print(a[i]+"\t");
        }
        System.out.println("\n============================");
    }
    public static void fun(Object a){
        System.out.println(a);
    }
}

7.总结

 

1. 数据库中每一张表对应java中两个类.[实体类(entity),操作类(dao)XXXDao]
   实体类---与表中列对应得类。
   操作类---对该表进行相应操作得类。--对表得增删改查。

2.异常处理try-catch-finally

对该表进行操作---封装实体类 和  操作类(添加 删除  修改  查询所有  根据id查询单条记录)。
包名: com.wzh.entity[实体类包]  com.wzh.dao[操作类包]

1. jdbc
(1)对数据库表进行了封装: [1]实体类  [2]操作类。

2. 包的命名必须都小写. 方法的命名首字母必须小写,而且要符合驼峰命名规则。
   类的命名:首字母大写,而且也要符合驼峰命名规则。

感谢观看!!!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值