JDBC简介

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

package com;

import java.sql.*;

public class Demo1 {

    public static void main(String[] args) {
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        //1、加载驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            //2、获得连接
            String username = "root";
            String password = "123456";
            String url = "jdbc:mysql://localhost:3306/yhp?serverTimezone=UTC";

            connection = DriverManager.getConnection(url, username, password);

            //3、定义sql,创建状态通道(进行sql语句的发送)
            statement = connection.createStatement();
            resultSet = statement.executeQuery("select * from emp1");//executeQuery(sql)执行查询

            //4、取出结果集信息
            while(resultSet.next()){//判断是否有下一跳数据
               //取出数据 resultSet.getXXX("列名"); xxx表示数据类型
                System.out.println("姓名: "+resultSet.getString("ename")
                        +" 工资: " +resultSet.getDouble("sal")
                +" 雇佣日期: "+resultSet.getDate("hiredate"));

            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {

            //5、关闭资源
            try {
                if (resultSet != null) {
                    resultSet.close();
                }

                if (statement != null) {
                    statement.close();
                }

                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}

package com;

import java.sql.*;

public class Demo2 {

    public static void main(String[] args) {
        Connection connection = null;
        Statement statement = null;
        //1、加载驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            //2、获得连接
            String username = "root";
            String password = "123456";
            String url = "jdbc:mysql://localhost:3306/yhp?serverTimezone=UTC";

            connection = DriverManager.getConnection(url, username, password);

            //3、定义sql,创建状态通道(进行sql语句的发送)
            statement = connection.createStatement();
//            int result = statement.executeUpdate("insert into emp1(ename,hiredate,sal)" +
//                    " values('aa','2020-1-1',20000);");//执行增删改时使用,返回结果受影响的行数

//            int result = statement.executeUpdate("update emp1 set sal=8888");//执行增删改时使用,返回结果受影响的行数

            int result = statement.executeUpdate("delete from emp1 where ename='aa'");//执行增删改时使用,返回结果受影响的行数

            if(result>0){
                System.out.println("执行成功"+",result=" +result);
            }else{
                System.out.println("执行失败");
            }


        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {

            //5、关闭资源
            try {
                if (statement != null) {
                    statement.close();
                }

                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}

在这里插入图片描述

package com;

import java.sql.*;

public class Demo3 {

    public static void main(String[] args) {
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        //1、加载驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            //2、获得连接
            String username = "root";
            String password = "123456";
            String url = "jdbc:mysql://localhost:3306/yhp?serverTimezone=UTC";

            connection = DriverManager.getConnection(url, username, password);

            //3、定义sql,创建状态通道(进行sql语句的发送)
            statement = connection.createStatement();
            String uname = "张三";
            String passwork = "'' or 1=1"; //sql注入,会导致帐号不存在的情况也登陆成功
            resultSet = statement.executeQuery("select * from users where username='"+uname+"'" +
                    " and upass=" + passwork);//executeQuery(sql)执行查询

            if(resultSet.next()){
                System.out.println("查询成功");
            }else{
                System.out.println("查询失败");
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {

            //5、关闭资源
            try {
                if (resultSet != null) {
                    resultSet.close();
                }

                if (statement != null) {
                    statement.close();
                }

                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}

在这里插入图片描述

在这里插入图片描述

package com;

import java.sql.*;

public class Demo4 {

    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement pps = null;
        ResultSet resultSet = null;
        //1、加载驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            //2、获得连接
            String username = "root";
            String password = "123456";
            String url = "jdbc:mysql://localhost:3306/yhp?serverTimezone=UTC";

            connection = DriverManager.getConnection(url, username, password);

            //3、定义sql,创建状态通道(进行sql语句的发送)
            String sql = "select * from users where username=? and upass=?";
            pps = connection.prepareStatement(sql);
            String uname = "张三";
            String upassword = "123"; //sql注入    "'' or 1=1"
            //给占位符赋值(下标、内容) 从1开始
            pps.setString(1,uname);
            pps.setString(2,upassword);
            //执行sql
            resultSet = pps.executeQuery();//executeQuery(sql)执行查询

            if(resultSet.next()){
                System.out.println("查询成功");
            }else{
                System.out.println("查询失败");
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {

            //5、关闭资源
            try {
                if (resultSet != null) {
                    resultSet.close();
                }

                if (pps != null) {
                    pps.close();
                }

                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

CREATE TABLE `student` ( 
`stuid` int(11) NOT NULL AUTO_INCREMENT,
 `stuname` varchar(255) DEFAULT NULL,
  `teacherid` int(11) DEFAULT NULL,
   PRIMARY KEY (`stuid`) 
   ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;

 INSERT INTO `student` VALUES ('1', 'aaa', '3');
 INSERT INTO `student` VALUES ('2', 'bb', '1'); 
 INSERT INTO `student` VALUES ('3', 'cc', '3');
 INSERT INTO `student` VALUES ('4', 'dd', '1'); 
 INSERT INTO `student` VALUES ('5', 'ee', '1');
 INSERT INTO `student` VALUES ('6', 'ff', '2'); 

DROP TABLE IF EXISTS `teacher`; 
CREATE TABLE `teacher` (
 `tid` int(11) NOT NULL AUTO_INCREMENT,
  `tname` varchar(255) DEFAULT NULL, 
  PRIMARY KEY (`tid`) 
  ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

 INSERT INTO `teacher` VALUES ('1', '张三老师'); 
 INSERT INTO `teacher` VALUES ('2', '李四老师');
 INSERT INTO `teacher` VALUES ('3', '王五');

在这里插入图片描述

package bin;

import java.util.List;

//一方
public class Teacher {
    private int tid;
    private String tName;
    //在一方创建存储多方数据的集合
    private List<Student> studentList;

    public int getTid() {
        return tid;
    }

    public void setTid(int tid) {
        this.tid = tid;
    }

    public String gettName() {
        return tName;
    }

    public void settName(String tName) {
        this.tName = tName;
    }

    public List<Student> getStudentList() {
        return studentList;
    }

    public void setStudentList(List<Student> studentList) {
        this.studentList = studentList;
    }
}

package bin;

import java.util.List;

public class Student {
    private int stuId;
    private String stuName;
    private int teacherId;

    //多对一:是在多方创建一个存储一方数据的对象
    private Teacher teacher;

    //配置多对多
    private List<Subject> subjectList;

    public List<Subject> getSubjectList() {
        return subjectList;
    }

    public void setSubjectList(List<Subject> subjectList) {
        this.subjectList = subjectList;
    }

    public int getStuId() {
        return stuId;
    }

    public void setStuId(int stuId) {
        this.stuId = stuId;
    }

    public String getStuName() {
        return stuName;
    }

    public void setStuName(String stuName) {
        this.stuName = stuName;
    }

    public int getTeacherId() {
        return teacherId;
    }

    public void setTeacherId(int teacherId) {
        this.teacherId = teacherId;
    }

    public Teacher getTeacher() {
        return teacher;
    }

    public void setTeacher(Teacher teacher) {
        this.teacher = teacher;
    }

}

在这里插入图片描述

package dao;

import bin.Student;
import bin.Teacher;

import java.util.List;

public interface TeacherDao {
    //定义操作方法
    //1、根据老师ID查询老师信息(学生的信息)
    public Teacher getById(int tid);

    //2、查询所有的学生(包含老师的信息)
    public List<Student> getAll();

    //查询全部学生
    public List<Student> getAllStudent(Class cla);

    //根据学生id查询学生信息
    public Student getByStuId(int id);
}

在这里插入图片描述

package dao.impl;

import bin.Student;
import bin.Teacher;
import dao.TeacherDao;
import util.DBUtils;
import util.DBUtils_C3P0;
import util.DBUtils_DBCP;
import util.DBUtils_Druid;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.*;

public class TeacherDaoimpl extends /*DBUtils_Druid*/ /*DBUtils_C3P0*/ DBUtils /*DBUtils_DBCP*/ implements TeacherDao {
    @Override
    public Teacher getById(int tid) {
        Connection connection = null;
        PreparedStatement pps = null;
        ResultSet resultSet = null;
        //1、加载驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            //2、获得连接
            String username = "root";
            String password = "123456";
            String url = "jdbc:mysql://localhost:3306/yhp3?serverTimezone=UTC";

            connection = DriverManager.getConnection(url, username, password);

            //3、定义sql,创建状态通道(进行sql语句的发送)
            String sql = "select * from student s,teacher t where s.teacherid=t.tid and t.tid=?";
            pps = connection.prepareStatement(sql);

            //给占位符赋值(下标、内容) 从1开始
            pps.setInt(1,tid);
            //执行sql
            resultSet = pps.executeQuery();//executeQuery(sql)执行查询

            Teacher teacher = new Teacher();
            List<Student> students = new ArrayList<>();
            while(resultSet.next()){
                //1、取出各自的信息
                teacher.setTid(resultSet.getInt("tid"));
                teacher.settName(resultSet.getString("tname"));

                Student student = new Student();
                student.setStuId(resultSet.getInt("stuid"));
                student.setStuName(resultSet.getString("stuname"));

                //2、建立学生和老师之间的关系
                students.add(student);
            }
            teacher.setStudentList(students);
            return teacher;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {

            //5、关闭资源
            try {
                if (resultSet != null) {
                    resultSet.close();
                }

                if (pps != null) {
                    pps.close();
                }

                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return null;
    }

    @Override
    public List<Student> getAll() {
        Connection connection = null;
        PreparedStatement pps = null;
        ResultSet resultSet = null;
        //1、加载驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            //2、获得连接
            String username = "root";
            String password = "123456";
            String url = "jdbc:mysql://localhost:3306/yhp3?serverTimezone=UTC";

            connection = DriverManager.getConnection(url, username, password);

            //3、定义sql,创建状态通道(进行sql语句的发送)
            String sql = "select * from student s,teacher t where s.teacherid=t.tid";
            pps = connection.prepareStatement(sql);

            //执行sql
            resultSet = pps.executeQuery();//executeQuery(sql)执行查询

            List<Student> students = new ArrayList<>();
            while(resultSet.next()){
                //1、取出各自的信息
                Student student = new Student();
                student.setStuId(resultSet.getInt("stuid"));
                student.setStuName(resultSet.getString("stuname"));

                Teacher teacher = new Teacher();
                teacher.setTid(resultSet.getInt("tid"));
                teacher.settName(resultSet.getString("tname"));

                //2、建立学生和老师之间的关系
                student.setTeacher(teacher);
                students.add(student);
            }
            return students;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {

            //5、关闭资源
            try {
                if (resultSet != null) {
                    resultSet.close();
                }

                if (pps != null) {
                    pps.close();
                }

                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return null;
    }

    @Override
    public List<Student> getAllStudent(Class cla) {
        Connection connection = null;
        PreparedStatement pps = null;
        ResultSet resultSet = null;
        //1、加载驱动s
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            //2、获得连接
            String username = "root";
            String password = "123456";
            String url = "jdbc:mysql://localhost:3306/yhp3?serverTimezone=UTC";

            connection = DriverManager.getConnection(url, username, password);

            //3、定义sql,创建状态通道(进行sql语句的发送)
            String sql = "select * from student s";
            pps = connection.prepareStatement(sql);

            //执行sql
            resultSet = pps.executeQuery();//executeQuery(sql)执行查询
            List students = new ArrayList();

            //得到数据库的查询结果的列信息
            ResultSetMetaData metaData = resultSet.getMetaData();//存储结果集信息
            int columnCount = metaData.getColumnCount();//得到列数
            String[] columnNames = new String[columnCount];
            for (int i = 0; i < columnCount; i++) {
                columnNames[i] = metaData.getColumnName(i+1);//列从1开始算
                System.out.println("columnNames = " + columnNames[i]);
            }
            //得到类中所有的方法
            Method[] declaredMethods = cla.getDeclaredMethods();
            while(resultSet.next()){
                //1、取出各自的信息
                try {
                    Object stu = cla.newInstance();
                    for (String columnName : columnNames) {
                        String methodName = "set" + columnName;
                        for (Method declaredMethod : declaredMethods) {
                            if(declaredMethod.getName().equalsIgnoreCase(methodName)){
                                declaredMethod.invoke(stu,resultSet.getObject(columnName));
                                break;
                            }
                        }
                    }
                    students.add(stu);
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
            return students;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {

            //5、关闭资源
            try {
                if (resultSet != null) {
                    resultSet.close();
                }

                if (pps != null) {
                    pps.close();
                }

                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return null;
    }

    @Override
    public Student getByStuId(int id) {
        try {
            String sql = "select * from student where stuid=?";
            List list = new ArrayList();
            list.add(id);
            ResultSet rs = query(sql,list);

            Student student = new Student();
            while(rs.next()){
                student.setStuId(rs.getInt("stuid"));
                student.setStuName(rs.getString("stuname"));
            }

            return student;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            closeAll();
        }

        return null;
    }
}


在这里插入图片描述

package test;

import bin.Student;
import bin.Teacher;
import dao.TeacherDao;
import dao.impl.TeacherDaoimpl;

import java.util.List;

public class Demo1 {

    public static void main(String[] args) {

        /*TeacherDao dao = new TeacherDaoimpl();
        Teacher teacher = dao.getById(1);
        System.out.println("老师姓名:"+teacher.gettName());
        List<Student> studentList = teacher.getStudentList();
        for(Student student : studentList){
            System.out.println("\t studentname:" + student.getStuName());
        }*/

        TeacherDao dao = new TeacherDaoimpl();
        List<Student> students = dao.getAll();
        for(Student student : students){
            System.out.println(student.getStuName()+"."+student.getTeacher().gettName());
        }
    }
}

在这里插入图片描述

CREATE TABLE `husband` (
 `husid` int(11) NOT NULL AUTO_INCREMENT,
  `husname` varchar(255) DEFAULT NULL,
   PRIMARY KEY (`husid`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; 

INSERT INTO `husband` VALUES ('1', '邓超'); 

DROP TABLE IF EXISTS `wife`; 
CREATE TABLE `wife` ( 
`wifeid` int(11) NOT NULL AUTO_INCREMENT,
 `wifename` varchar(255) DEFAULT NULL, 
 `hid` int(11) DEFAULT NULL,
  PRIMARY KEY (`wifeid`),
   UNIQUE KEY `uq_wife_hid` (`hid`)
 ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

 INSERT INTO `wife` VALUES ('1', '孙俪', '1');

在这里插入图片描述

package bin;

public class Husband {

    private int husId;
    private String husName;

    public Wife wife;

    public int getHusId() {
        return husId;
    }

    public void setHusId(int husId) {
        this.husId = husId;
    }

    public String getHusName() {
        return husName;
    }

    public void setHusName(String husName) {
        this.husName = husName;
    }

    public Wife getWife() {
        return wife;
    }

    public void setWife(Wife wife) {
        this.wife = wife;
    }
}

package bin;

public class Wife {

    private int wifeId;
    private String wifeName;
    private int hid;

    private  Husband husband;

    public int getWifeId() {
        return wifeId;
    }

    public void setWifeId(int wifeId) {
        this.wifeId = wifeId;
    }

    public String getWifeName() {
        return wifeName;
    }

    public void setWifeName(String wifeName) {
        this.wifeName = wifeName;
    }

    public Husband getHusband() {
        return husband;
    }

    public void setHusband(Husband husband) {
        this.husband = husband;
    }
}

在这里插入图片描述

package dao;

import bin.Husband;
import bin.Wife;

public interface WifeDao {

    //查询妻子信息(包含丈夫信息)
    public Wife getWife(int wid);

    //查询丈夫信息(包含妻子信息)
    public Husband getHus(int hid);
}

在这里插入图片描述

package dao.impl;

import bin.Husband;
import bin.Wife;
import dao.WifeDao;

import java.sql.*;

public class WifeDaoimpl implements WifeDao {


    @Override
    public Wife getWife(int wid) {
        Connection connection = null;
        PreparedStatement pps = null;
        ResultSet resultSet = null;
        //1、加载驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            //2、获得连接
            String username = "root";
            String password = "123456";
            String url = "jdbc:mysql://localhost:3306/yhp3?serverTimezone=UTC";

            connection = DriverManager.getConnection(url, username, password);

            //3、定义sql,创建状态通道(进行sql语句的发送)
            String sql = "select * from wife w,husband h where w.hid=h.husid and w.wifeid=?";
            pps = connection.prepareStatement(sql);
            pps.setInt(1,wid);
            //执行sql
            resultSet = pps.executeQuery();//executeQuery(sql)执行查询

            Wife wife = new Wife();
            while(resultSet.next()){
                //1、取出各自的信息
                wife.setWifeId(resultSet.getInt("wifeid"));
                wife.setWifeName(resultSet.getString("wifename"));

                Husband husband = new Husband();
                husband.setHusId(resultSet.getInt("husid"));
                husband.setHusName(resultSet.getString("husname"));

                //建立妻子和丈夫的关系
                wife.setHusband(husband);
            }
            return wife;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {

            //5、关闭资源
            try {
                if (resultSet != null) {
                    resultSet.close();
                }

                if (pps != null) {
                    pps.close();
                }

                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return null;
    }

    @Override
    public Husband getHus(int hid) {
        Connection connection = null;
        PreparedStatement pps = null;
        ResultSet resultSet = null;
        //1、加载驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            //2、获得连接
            String username = "root";
            String password = "123456";
            String url = "jdbc:mysql://localhost:3306/yhp3?serverTimezone=UTC";

            connection = DriverManager.getConnection(url, username, password);

            //3、定义sql,创建状态通道(进行sql语句的发送)
            String sql = "select * from wife w,husband h where w.hid=h.husid and h.husid=?";
            pps = connection.prepareStatement(sql);
            pps.setInt(1,hid);
            //执行sql
            resultSet = pps.executeQuery();//executeQuery(sql)执行查询

            Husband husband = new Husband();
            while(resultSet.next()){
                //1、取出各自的信息
                husband.setHusId(resultSet.getInt("husid"));
                husband.setHusName(resultSet.getString("husname"));

                Wife wife = new Wife();
                wife.setWifeId(resultSet.getInt("wifeid"));
                wife.setWifeName(resultSet.getString("wifename"));

                //建立妻子和丈夫的关系
                husband.setWife(wife);
            }
            return husband;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {

            //5、关闭资源
            try {
                if (resultSet != null) {
                    resultSet.close();
                }

                if (pps != null) {
                    pps.close();
                }

                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return null;
    }
}

在这里插入图片描述

package test;

import bin.Husband;
import bin.Wife;
import dao.impl.WifeDaoimpl;

public class Demo2 {

    public static void main(String[] args) {
        WifeDaoimpl wifeDao = new WifeDaoimpl();
        Wife wife = wifeDao.getWife(1);
        System.out.println(wife.getWifeName()+","+wife.getHusband().getHusName());

        Husband husband = wifeDao.getHus(1);
        System.out.println(husband.getHusName()+","+husband.getWife().getWifeName());
    }
}

在这里插入图片描述
在这里插入图片描述

CREATE TABLE `middle` (
 `middleid` int(11) NOT NULL AUTO_INCREMENT,
  `stuid` int(11) DEFAULT NULL,
   `subid` int(11) DEFAULT NULL, 
   PRIMARY KEY (`middleid`)
 ) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;

 -- ---------------------------- 
 -- Records of middle -- 
 ----------------------------
 INSERT INTO `middle` VALUES ('1', '1', '1');
 INSERT INTO `middle` VALUES ('2', '1', '2'); 
 INSERT INTO `middle` VALUES ('3', '1', '3'); 
 INSERT INTO `middle` VALUES ('4', '1', '5'); 
 INSERT INTO `middle` VALUES ('5', '2', '2'); 
 INSERT INTO `middle` VALUES ('6', '3', '2'); 
 INSERT INTO `middle` VALUES ('7', '4', '2'); 
 INSERT INTO `middle` VALUES ('8', '5', '2'); 
 INSERT INTO `middle` VALUES ('9', '6', '2'); 

-- ---------------------------- 
-- Table structure for `student` 
-- ---------------------------- 
DROP TABLE IF EXISTS `student`; 
CREATE TABLE `student` ( 
`stuid` int(11) NOT NULL AUTO_INCREMENT, 
`stuname` varchar(255) DEFAULT NULL, 
`teacherid` int(11) DEFAULT NULL, 
PRIMARY KEY (`stuid`) 
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;

 -- ---------------------------- 
 -- Records of student 
 -- ---------------------------- 
 INSERT INTO `student` VALUES ('1', '张三', '3'); 
 INSERT INTO `student` VALUES ('2', '李四', '1'); 
 INSERT INTO `student` VALUES ('3', '王五', '3'); 
 INSERT INTO `student` VALUES ('4', '赵六', '1'); 
 INSERT INTO `student` VALUES ('5', '花花', '1');
 INSERT INTO `student` VALUES ('6', '潇潇', '2'); 

-- ---------------------------- 
-- Table structure for `subject` 
-- ---------------------------- 
DROP TABLE IF EXISTS `subject`; 
CREATE TABLE `subject` ( 
`subid` int(11) NOT NULL AUTO_INCREMENT, 
`subname` varchar(255) DEFAULT NULL, 
PRIMARY KEY (`subid`) 
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8; 

-- ---------------------------- 
-- Records of subject 
-- ---------------------------- 
INSERT INTO `subject` VALUES ('1', 'java'); 
INSERT INTO `subject` VALUES ('2', 'ui'); 
INSERT INTO `subject` VALUES ('3', 'h5'); 
INSERT INTO `subject` VALUES ('4', 'c'); 
INSERT INTO `subject` VALUES ('5', 'c++'); 
INSERT INTO `subject` VALUES ('6', 'c#');

在这里插入图片描述

package bin;

import java.util.List;

public class Subject {

    private int subId;
    private String subName;
    private List<Student> studentList;

    public int getSubId() {
        return subId;
    }

    public void setSubId(int subId) {
        this.subId = subId;
    }

    public String getSubName() {
        return subName;
    }

    public void setSubName(String subName) {
        this.subName = subName;
    }

    public List<Student> getStudentList() {
        return studentList;
    }

    public void setStudentList(List<Student> studentList) {
        this.studentList = studentList;
    }
}

package bin;

import java.util.List;

public class Student {
    private int stuId;
    private String stuName;
    private int teacherId;

    //多对一:是在多方创建一个存储一方数据的对象
    private Teacher teacher;

    //配置多对多
    private List<Subject> subjectList;

    public List<Subject> getSubjectList() {
        return subjectList;
    }

    public void setSubjectList(List<Subject> subjectList) {
        this.subjectList = subjectList;
    }

    public int getStuId() {
        return stuId;
    }

    public void setStuId(int stuId) {
        this.stuId = stuId;
    }

    public String getStuName() {
        return stuName;
    }

    public void setStuName(String stuName) {
        this.stuName = stuName;
    }

    public int getTeacherId() {
        return teacherId;
    }

    public void setTeacherId(int teacherId) {
        this.teacherId = teacherId;
    }

    public Teacher getTeacher() {
        return teacher;
    }

    public void setTeacher(Teacher teacher) {
        this.teacher = teacher;
    }

}

在这里插入图片描述

package dao;

import bin.Student;
import bin.Subject;

public interface SubjectDao {

    //查询学生信息(查询所学科目)
    public Student findById(int id);

    //查询某个科目及对应的学生姓名
    public Subject findBysubId(int subId);
}

在这里插入图片描述

package dao.impl;

import bin.Student;
import bin.Subject;
import bin.Teacher;
import dao.SubjectDao;

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

public class SubjectDaoimpl implements SubjectDao {
    @Override
    public Student findById(int id) {
        Connection connection = null;
        PreparedStatement pps = null;
        ResultSet resultSet = null;
        //1、加载驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            //2、获得连接
            String username = "root";
            String password = "123456";
            String url = "jdbc:mysql://localhost:3306/yhp3?serverTimezone=UTC";

            connection = DriverManager.getConnection(url, username, password);

            //3、定义sql,创建状态通道(进行sql语句的发送)
            String sql = "select * from student s,subject su,middle m,teacher t where s.stuid=m.stuid" +
                    " and su.subid=m.subid and t.tid=s.teacherid and s.stuid=?;";
            pps = connection.prepareStatement(sql);

            //给占位符赋值(下标、内容) 从1开始
            pps.setInt(1,id);
            //执行sql
            resultSet = pps.executeQuery();//executeQuery(sql)执行查询

            Student student = new Student();
            List<Subject> subjects = new ArrayList<>();
            while(resultSet.next()){
                //1、取出各自的信息
                student.setStuId(resultSet.getInt("stuid"));
                student.setStuName(resultSet.getString("stuname"));

                Teacher teacher = new Teacher();
                teacher.setTid(resultSet.getInt("tid"));
                teacher.settName(resultSet.getString("tname"));
                student.setTeacher(teacher);

                Subject subject = new Subject();
                subject.setSubId(resultSet.getInt("subid"));
                subject.setSubName(resultSet.getString("subname"));
                subjects.add(subject);
            }
            student.setSubjectList(subjects);
            return student;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {

            //5、关闭资源
            try {
                if (resultSet != null) {
                    resultSet.close();
                }

                if (pps != null) {
                    pps.close();
                }

                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return null;
    }

    @Override
    public Subject findBysubId(int subId) {
        Connection connection = null;
        PreparedStatement pps = null;
        ResultSet resultSet = null;
        //1、加载驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            //2、获得连接
            String username = "root";
            String password = "123456";
            String url = "jdbc:mysql://localhost:3306/yhp3?serverTimezone=UTC";

            connection = DriverManager.getConnection(url, username, password);

            //3、定义sql,创建状态通道(进行sql语句的发送)
            String sql = "select * from student s,subject su,middle m where s.stuid=m.stuid " +
                    "and su.subid=m.subid and su.subid=?";
            pps = connection.prepareStatement(sql);

            //给占位符赋值(下标、内容) 从1开始
            pps.setInt(1,subId);
            //执行sql
            resultSet = pps.executeQuery();//executeQuery(sql)执行查询

            Subject subject = new Subject();
            List<Student> students = new ArrayList<>();
            while(resultSet.next()){
                //1、取出各自的信息
                subject.setSubId(resultSet.getInt("subid"));
                subject.setSubName(resultSet.getString("subname"));

                Student student = new Student();
                student.setStuId(resultSet.getInt("stuid"));
                student.setStuName(resultSet.getString("stuname"));
                students.add(student);
            }
            subject.setStudentList(students);
            return subject;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {

            //5、关闭资源
            try {
                if (resultSet != null) {
                    resultSet.close();
                }

                if (pps != null) {
                    pps.close();
                }

                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return null;
    }
}

在这里插入图片描述

package test;

import bin.Student;
import bin.Subject;
import dao.impl.SubjectDaoimpl;

import java.util.List;

public class Demo3 {

    public static void main(String[] args) {

        SubjectDaoimpl subjectDao = new SubjectDaoimpl();
        Student student = subjectDao.findById(1);
        System.out.println(student.getStuName());
        System.out.println(student.getTeacher().gettName());
        List<Subject> subjects = student.getSubjectList();
        for(Subject subject : subjects){
            System.out.println("\t" + subject.getSubName());
        }

        /*SubjectDaoimpl subjectDao = new SubjectDaoimpl();
        Subject subject = subjectDao.findBysubId(2);
        System.out.println(subject.getSubName());
        List<Student> students = subject.getStudentList();
        for(Student student : students){
            System.out.println("\t" + student.getStuName());
        }*/
    }
}

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

conn.commit( );

在这里插入图片描述

conn.rollback( );

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

package com;

import java.sql.*;

public class Demo5 {

    public static void main(String[] args) {
        Connection connection = null;
        Statement statement = null;
        Savepoint abc = null;
        //1、加载驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            //2、获得连接
            String username = "root";
            String password = "123456";
            String url = "jdbc:mysql://localhost:3306/yhp?serverTimezone=UTC";

            connection = DriverManager.getConnection(url, username, password);
            connection.setAutoCommit(false);
            //3、定义sql,创建状态通道(进行sql语句的发送)
            statement = connection.createStatement();
//            int result = statement.executeUpdate("insert into emp1(ename,hiredate,sal)" +
//                    " values('aa','2020-1-1',20000);");//执行增删改时使用,返回结果受影响的行数

//            int result = statement.executeUpdate("update emp1 set sal=8888");//执行增删改时使用,返回结果受影响的行数

            int result = statement.executeUpdate("insert into emp1(ename,hiredate,sal)"  +
                    " values('张三a','2020-1-1',2000);");//执行增删改时使用,返回结果受影响的行数
            abc = connection.setSavepoint("abc");
            //System.out.println(5/0);
            int result2 = statement.executeUpdate("insert into emp1(ename,hiredate,sal)"  +
                    " values('张三b','2020-1-1',2000);");//执行增删改时使用,返回结果受影响的行数
            System.out.println(5/0);
            //通过代码方式提交事务
            connection.commit();
            if(result>0){
                System.out.println("执行成功"+",result=" +result);
            }else{
                System.out.println("执行失败");
            }


        } catch (Exception e) {
            e.printStackTrace();
            try {
                //connection.rollback();
                connection.rollback(abc);
                connection.commit();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        } finally {

            //5、关闭资源
            try {
                if (statement != null) {
                    statement.close();
                }

                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}

在这里插入图片描述

package com;

import java.sql.*;

public class Demo6 {

    public static void main(String[] args) {
        Connection connection = null;
        Statement statement = null;
        Savepoint abc = null;
        //1、加载驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            //2、获得连接
            String username = "root";
            String password = "123456";
            String url = "jdbc:mysql://localhost:3306/yhp3?serverTimezone=UTC";

            connection = DriverManager.getConnection(url, username, password);
            //如果为自动提交,业务逻辑出错的时候,数据库数据也应该回滚,而不是被更改
            //connection.setAutoCommit(false);//设置成手动提交
            //3、定义sql,创建状态通道(进行sql语句的发送)
            statement = connection.createStatement();
//            int result = statement.executeUpdate("insert into emp1(ename,hiredate,sal)" +
//                    " values('aa','2020-1-1',20000);");//执行增删改时使用,返回结果受影响的行数

//            int result = statement.executeUpdate("update emp1 set sal=8888");//执行增删改时使用,返回结果受影响的行数

            int result = statement.executeUpdate("update money set yue=yue-100 where userid=1");//执行增删改时使用,返回结果受影响的行数

            int result2 = statement.executeUpdate("update money set yue=yue+100 where userid=2");//执行增删改时使用,返回结果受影响的行数
            System.out.println(5/0);
            //通过代码方式提交事务
            //connection.commit();
            if(result>0){
                System.out.println("执行成功"+",result=" +result);
            }else{
                System.out.println("执行失败");
            }


        } catch (Exception e) {
            e.printStackTrace();
            try {
                connection.rollback();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        } finally {

            //5、关闭资源
            try {
                if (statement != null) {
                    statement.close();
                }

                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}

在这里插入图片描述
在这里插入图片描述

package com;

import java.sql.*;

public class StatemenBatch {

    public static void main(String[] args) {
        Connection connection = null;
        Statement statement = null;
        Savepoint abc = null;
        //1、加载驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            //2、获得连接
            String username = "root";
            String password = "123456";
            String url = "jdbc:mysql://localhost:3306/yhp3?serverTimezone=UTC";

            connection = DriverManager.getConnection(url, username, password);
            //如果为自动提交,业务逻辑出错的时候,数据库数据也应该回滚,而不是被更改
            connection.setAutoCommit(false);//设置成手动提交
            //3、定义sql,创建状态通道(进行sql语句的发送)
            statement = connection.createStatement();

            //定义sql
            String sql1 = "insert into teacher(tname) values('张三a')";
            statement.addBatch(sql1);

            String sql2 = "insert into teacher(tname) values('张三b')";
            statement.addBatch(sql2);

            String sql3 = "insert into teacher(tname) values('张三c')";
            statement.addBatch(sql3);

            String sql4 = "insert into teacher(tname) values('张三d')";
            statement.addBatch(sql4);

            int[] ints = statement.executeBatch();//执行增删改时使用,返回结果受影响的行数

            for(int anInt : ints){
                System.out.println("anInt="+anInt);
            }
            connection.commit();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                connection.rollback();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        } finally {

            //5、关闭资源
            try {
                if (statement != null) {
                    statement.close();
                }

                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}

在这里插入图片描述
在这里插入图片描述

package com;

import java.sql.*;

public class PrepareStatemenBatch {

    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement pps = null;
        Savepoint abc = null;
        //1、加载驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            //2、获得连接
            String username = "root";
            String password = "123456";
            String url = "jdbc:mysql://localhost:3306/yhp3?serverTimezone=UTC";

            connection = DriverManager.getConnection(url, username, password);
            //如果为自动提交,业务逻辑出错的时候,数据库数据也应该回滚,而不是被更改
            connection.setAutoCommit(false);//设置成手动提交
            //3、定义sql,创建状态通道(进行sql语句的发送)
            pps = connection.prepareStatement("insert into teacher(tname) values(?)");

            //赋值
            pps.setString(1,"李四A");
            pps.addBatch();

            pps.setString(1,"李四B");
            pps.addBatch();

            pps.setString(1,"李四C");
            pps.addBatch();

            pps.setString(1,"李四D");
            pps.addBatch();

            int[] ints = pps.executeBatch();//执行增删改时使用,返回结果受影响的行数
            connection.commit();
            for(int anInt : ints){
                System.out.println("anInt="+anInt);
            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                connection.rollback();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        } finally {

            //5、关闭资源
            try {
                if (pps != null) {
                    pps.close();
                }

                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}

在这里插入图片描述
在这里插入图片描述

package dao;

import bin.Student;
import bin.Teacher;

import java.util.List;

public interface TeacherDao {
    //定义操作方法
    //1、根据老师ID查询老师信息(学生的信息)
    public Teacher getById(int tid);

    //2、查询所有的学生(包含老师的信息)
    public List<Student> getAll();

    //查询全部学生
    public List<Student> getAllStudent(Class cla);

    //根据学生id查询学生信息
    public Student getByStuId(int id);
}

在这里插入图片描述

package dao.impl;

import bin.Student;
import bin.Teacher;
import dao.TeacherDao;
import util.DBUtils;
import util.DBUtils_C3P0;
import util.DBUtils_DBCP;
import util.DBUtils_Druid;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.*;

public class TeacherDaoimpl extends /*DBUtils_Druid*/ /*DBUtils_C3P0*/ DBUtils /*DBUtils_DBCP*/ implements TeacherDao {
    @Override
    public Teacher getById(int tid) {
        Connection connection = null;
        PreparedStatement pps = null;
        ResultSet resultSet = null;
        //1、加载驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            //2、获得连接
            String username = "root";
            String password = "123456";
            String url = "jdbc:mysql://localhost:3306/yhp3?serverTimezone=UTC";

            connection = DriverManager.getConnection(url, username, password);

            //3、定义sql,创建状态通道(进行sql语句的发送)
            String sql = "select * from student s,teacher t where s.teacherid=t.tid and t.tid=?";
            pps = connection.prepareStatement(sql);

            //给占位符赋值(下标、内容) 从1开始
            pps.setInt(1,tid);
            //执行sql
            resultSet = pps.executeQuery();//executeQuery(sql)执行查询

            Teacher teacher = new Teacher();
            List<Student> students = new ArrayList<>();
            while(resultSet.next()){
                //1、取出各自的信息
                teacher.setTid(resultSet.getInt("tid"));
                teacher.settName(resultSet.getString("tname"));

                Student student = new Student();
                student.setStuId(resultSet.getInt("stuid"));
                student.setStuName(resultSet.getString("stuname"));

                //2、建立学生和老师之间的关系
                students.add(student);
            }
            teacher.setStudentList(students);
            return teacher;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {

            //5、关闭资源
            try {
                if (resultSet != null) {
                    resultSet.close();
                }

                if (pps != null) {
                    pps.close();
                }

                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return null;
    }

    @Override
    public List<Student> getAll() {
        Connection connection = null;
        PreparedStatement pps = null;
        ResultSet resultSet = null;
        //1、加载驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            //2、获得连接
            String username = "root";
            String password = "123456";
            String url = "jdbc:mysql://localhost:3306/yhp3?serverTimezone=UTC";

            connection = DriverManager.getConnection(url, username, password);

            //3、定义sql,创建状态通道(进行sql语句的发送)
            String sql = "select * from student s,teacher t where s.teacherid=t.tid";
            pps = connection.prepareStatement(sql);

            //执行sql
            resultSet = pps.executeQuery();//executeQuery(sql)执行查询

            List<Student> students = new ArrayList<>();
            while(resultSet.next()){
                //1、取出各自的信息
                Student student = new Student();
                student.setStuId(resultSet.getInt("stuid"));
                student.setStuName(resultSet.getString("stuname"));

                Teacher teacher = new Teacher();
                teacher.setTid(resultSet.getInt("tid"));
                teacher.settName(resultSet.getString("tname"));

                //2、建立学生和老师之间的关系
                student.setTeacher(teacher);
                students.add(student);
            }
            return students;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {

            //5、关闭资源
            try {
                if (resultSet != null) {
                    resultSet.close();
                }

                if (pps != null) {
                    pps.close();
                }

                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return null;
    }

    @Override
    public List<Student> getAllStudent(Class cla) {
        Connection connection = null;
        PreparedStatement pps = null;
        ResultSet resultSet = null;
        //1、加载驱动s
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            //2、获得连接
            String username = "root";
            String password = "123456";
            String url = "jdbc:mysql://localhost:3306/yhp3?serverTimezone=UTC";

            connection = DriverManager.getConnection(url, username, password);

            //3、定义sql,创建状态通道(进行sql语句的发送)
            String sql = "select * from student s";
            pps = connection.prepareStatement(sql);

            //执行sql
            resultSet = pps.executeQuery();//executeQuery(sql)执行查询
            List students = new ArrayList();

            //得到数据库的查询结果的列信息
            ResultSetMetaData metaData = resultSet.getMetaData();//存储结果集信息
            int columnCount = metaData.getColumnCount();//得到列数
            String[] columnNames = new String[columnCount];
            for (int i = 0; i < columnCount; i++) {
                columnNames[i] = metaData.getColumnName(i+1);//列从1开始算
                System.out.println("columnNames = " + columnNames[i]);
            }
            //得到类中所有的方法
            Method[] declaredMethods = cla.getDeclaredMethods();
            while(resultSet.next()){
                //1、取出各自的信息
                try {
                    Object stu = cla.newInstance();
                    for (String columnName : columnNames) {
                        String methodName = "set" + columnName;
                        for (Method declaredMethod : declaredMethods) {
                            if(declaredMethod.getName().equalsIgnoreCase(methodName)){
                                declaredMethod.invoke(stu,resultSet.getObject(columnName));
                                break;
                            }
                        }
                    }
                    students.add(stu);
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
            return students;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {

            //5、关闭资源
            try {
                if (resultSet != null) {
                    resultSet.close();
                }

                if (pps != null) {
                    pps.close();
                }

                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return null;
    }

    @Override
    public Student getByStuId(int id) {
        try {
            String sql = "select * from student where stuid=?";
            List list = new ArrayList();
            list.add(id);
            ResultSet rs = query(sql,list);

            Student student = new Student();
            while(rs.next()){
                student.setStuId(rs.getInt("stuid"));
                student.setStuName(rs.getString("stuname"));
            }

            return student;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            closeAll();
        }

        return null;
    }
}

package test;

import bin.Student;
import dao.impl.TeacherDaoimpl;

import java.util.List;

public class Demo4 {

    public static void main(String[] args) {
        TeacherDaoimpl teacherDao = new TeacherDaoimpl();
        List<Student> allStudent = teacherDao.getAllStudent(Student.class);
        for (Student student : allStudent) {
            System.out.println(student.getStuId() + "," + student.getStuName()+","+student.getTeacherId());
        }

        /*Student byStuId = teacherDao.getByStuId(1);
        System.out.println(byStuId.getStuId()+","+byStuId.getStuName());*/
    }
}

在这里插入图片描述
TeacherDao

package dao;

import bin.Student;
import bin.Teacher;

import java.util.List;

public interface TeacherDao {
    //定义操作方法
    //1、根据老师ID查询老师信息(学生的信息)
    public Teacher getById(int tid);

    //2、查询所有的学生(包含老师的信息)
    public List<Student> getAll();

    //查询全部学生
    public List<Student> getAllStudent(Class cla);

    //根据学生id查询学生信息
    public Student getByStuId(int id);
}

TeacherDaoimpl

package dao.impl;

import bin.Student;
import bin.Teacher;
import dao.TeacherDao;
import util.DBUtils;
import util.DBUtils_C3P0;
import util.DBUtils_DBCP;
import util.DBUtils_Druid;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.*;

public class TeacherDaoimpl extends /*DBUtils_Druid*/ /*DBUtils_C3P0*/ DBUtils /*DBUtils_DBCP*/ implements TeacherDao {
    @Override
    public Teacher getById(int tid) {
        Connection connection = null;
        PreparedStatement pps = null;
        ResultSet resultSet = null;
        //1、加载驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            //2、获得连接
            String username = "root";
            String password = "123456";
            String url = "jdbc:mysql://localhost:3306/yhp3?serverTimezone=UTC";

            connection = DriverManager.getConnection(url, username, password);

            //3、定义sql,创建状态通道(进行sql语句的发送)
            String sql = "select * from student s,teacher t where s.teacherid=t.tid and t.tid=?";
            pps = connection.prepareStatement(sql);

            //给占位符赋值(下标、内容) 从1开始
            pps.setInt(1,tid);
            //执行sql
            resultSet = pps.executeQuery();//executeQuery(sql)执行查询

            Teacher teacher = new Teacher();
            List<Student> students = new ArrayList<>();
            while(resultSet.next()){
                //1、取出各自的信息
                teacher.setTid(resultSet.getInt("tid"));
                teacher.settName(resultSet.getString("tname"));

                Student student = new Student();
                student.setStuId(resultSet.getInt("stuid"));
                student.setStuName(resultSet.getString("stuname"));

                //2、建立学生和老师之间的关系
                students.add(student);
            }
            teacher.setStudentList(students);
            return teacher;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {

            //5、关闭资源
            try {
                if (resultSet != null) {
                    resultSet.close();
                }

                if (pps != null) {
                    pps.close();
                }

                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return null;
    }

    @Override
    public List<Student> getAll() {
        Connection connection = null;
        PreparedStatement pps = null;
        ResultSet resultSet = null;
        //1、加载驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            //2、获得连接
            String username = "root";
            String password = "123456";
            String url = "jdbc:mysql://localhost:3306/yhp3?serverTimezone=UTC";

            connection = DriverManager.getConnection(url, username, password);

            //3、定义sql,创建状态通道(进行sql语句的发送)
            String sql = "select * from student s,teacher t where s.teacherid=t.tid";
            pps = connection.prepareStatement(sql);

            //执行sql
            resultSet = pps.executeQuery();//executeQuery(sql)执行查询

            List<Student> students = new ArrayList<>();
            while(resultSet.next()){
                //1、取出各自的信息
                Student student = new Student();
                student.setStuId(resultSet.getInt("stuid"));
                student.setStuName(resultSet.getString("stuname"));

                Teacher teacher = new Teacher();
                teacher.setTid(resultSet.getInt("tid"));
                teacher.settName(resultSet.getString("tname"));

                //2、建立学生和老师之间的关系
                student.setTeacher(teacher);
                students.add(student);
            }
            return students;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {

            //5、关闭资源
            try {
                if (resultSet != null) {
                    resultSet.close();
                }

                if (pps != null) {
                    pps.close();
                }

                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return null;
    }

    @Override
    public List<Student> getAllStudent(Class cla) {
        Connection connection = null;
        PreparedStatement pps = null;
        ResultSet resultSet = null;
        //1、加载驱动s
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            //2、获得连接
            String username = "root";
            String password = "123456";
            String url = "jdbc:mysql://localhost:3306/yhp3?serverTimezone=UTC";

            connection = DriverManager.getConnection(url, username, password);

            //3、定义sql,创建状态通道(进行sql语句的发送)
            String sql = "select * from student s";
            pps = connection.prepareStatement(sql);

            //执行sql
            resultSet = pps.executeQuery();//executeQuery(sql)执行查询
            List students = new ArrayList();

            //得到数据库的查询结果的列信息
            ResultSetMetaData metaData = resultSet.getMetaData();//存储结果集信息
            int columnCount = metaData.getColumnCount();//得到列数
            String[] columnNames = new String[columnCount];
            for (int i = 0; i < columnCount; i++) {
                columnNames[i] = metaData.getColumnName(i+1);//列从1开始算
                System.out.println("columnNames = " + columnNames[i]);
            }
            //得到类中所有的方法
            Method[] declaredMethods = cla.getDeclaredMethods();
            while(resultSet.next()){
                //1、取出各自的信息
                try {
                    Object stu = cla.newInstance();
                    for (String columnName : columnNames) {
                        String methodName = "set" + columnName;
                        for (Method declaredMethod : declaredMethods) {
                            if(declaredMethod.getName().equalsIgnoreCase(methodName)){
                                declaredMethod.invoke(stu,resultSet.getObject(columnName));
                                break;
                            }
                        }
                    }
                    students.add(stu);
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
            return students;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {

            //5、关闭资源
            try {
                if (resultSet != null) {
                    resultSet.close();
                }

                if (pps != null) {
                    pps.close();
                }

                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return null;
    }

    @Override
    public Student getByStuId(int id) {
        try {
            String sql = "select * from student where stuid=?";
            List list = new ArrayList();
            list.add(id);
            ResultSet rs = query(sql,list);

            Student student = new Student();
            while(rs.next()){
                student.setStuId(rs.getInt("stuid"));
                student.setStuName(rs.getString("stuname"));
            }

            return student;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            closeAll();
        }

        return null;
    }
}

DBUtils

package util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.List;
import java.util.Properties;
import java.util.ResourceBundle;

public class DBUtils {
    //1、定义变量
    private Connection connection;
    private PreparedStatement pps;
    private ResultSet resultSet;
    private int count;  //存储受影响的行数

    private static String dirverName;
    private static String username;
    private static String userpass;
    private static String url;

    //2、加载驱动
    static {
        /*InputStream inputStream = DBUtils.class.getClassLoader() .getResourceAsStream("db.properties");
        Properties properties = new Properties();
        try {
            properties.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        dirverName = properties.getProperty("driverclass");
        url = properties.getProperty("url");
        username = properties.getProperty("uname");
        userpass = properties.getProperty("upass");*/
        //参数只写属性文件名即可,不需要写后缀
        ResourceBundle bundle = ResourceBundle.getBundle("db");
        dirverName = bundle.getString("driverclass");
        url = bundle.getString("url");
        username = bundle.getString("uname");
        userpass = bundle.getString("upass");
        try {
            Class.forName(dirverName);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    //3、获得链接
    protected Connection getConnection(){
        try {
            connection = DriverManager.getConnection(url,username,userpass);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return connection;
    }

    //4、得到预状态通道
    protected PreparedStatement getPps(String sql){
        try {
            pps = getConnection().prepareStatement(sql);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return pps;
    }

    //5、绑定参数 List保存的是给占位符所赋的值
    protected void param(List list){
        if(list!=null && list.size()>0){
            for (int i=0; i<list.size(); i++) {
                try {
                    pps.setObject(i+1, list.get(i));
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }

    //6、执行操作(增删改+查询)
    protected int update(String sql, List list){
        getPps(sql);
        param(list);

        try {
            count = pps.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return count;
    }

    //7、查询
    protected ResultSet query(String sql, List list){
        getPps(sql);
        param(list);
        try {
            resultSet = pps.executeQuery();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return resultSet;
    }

    //8、关闭资源
    protected void closeAll(){
        try {
            if (connection != null) {
                connection.close();
            }

            if (pps != null) {
                pps.close();
            }

            if (resultSet != null) {
                resultSet.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}

DBUtils_C3P0

package util;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbcp.BasicDataSource;

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

public class DBUtils_C3P0 {
    //1、定义变量
    private Connection connection;
    private PreparedStatement pps;
    private ResultSet resultSet;
    private int count;  //存储受影响的行数

    private static String dirverName;
    private static String username;
    private static String userpass;
    private static String url;
    //C3P0
    private static ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();

    //2、加载驱动
    static {

    }

    //3、获得链接
    protected Connection getConnection(){
        try {
            connection = comboPooledDataSource.getConnection();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return connection;
    }

    //4、得到预状态通道
    protected PreparedStatement getPps(String sql){
        try {
            pps = getConnection().prepareStatement(sql);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return pps;
    }

    //5、绑定参数 List保存的是给占位符所赋的值
    protected void param(List list){
        if(list!=null && list.size()>0){
            for (int i=0; i<list.size(); i++) {
                try {
                    pps.setObject(i+1, list.get(i));
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }

    //6、执行操作(增删改+查询)
    protected int update(String sql, List list){
        getPps(sql);
        param(list);

        try {
            count = pps.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return count;
    }

    //7、查询
    protected ResultSet query(String sql, List list){
        getPps(sql);
        param(list);
        try {
            resultSet = pps.executeQuery();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return resultSet;
    }

    //8、关闭资源
    protected void closeAll(){
        try {
            if (connection != null) {
                connection.close();
            }

            if (pps != null) {
                pps.close();
            }

            if (resultSet != null) {
                resultSet.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}

DBUtils_DBCP

package util;

import org.apache.commons.dbcp.BasicDataSource;

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

public class DBUtils_DBCP {
    //1、定义变量
    private Connection connection;
    private PreparedStatement pps;
    private ResultSet resultSet;
    private int count;  //存储受影响的行数

    private static String dirverName;
    private static String username;
    private static String userpass;
    private static String url;

    private static BasicDataSource basicDataSource = new BasicDataSource();

    //2、加载驱动
    static {
        ResourceBundle bundle = ResourceBundle.getBundle("db");
        dirverName = bundle.getString("driverclass");
        url = bundle.getString("url");
        username = bundle.getString("uname");
        userpass = bundle.getString("upass");

        basicDataSource.setUsername(username);
        basicDataSource.setPassword(userpass);
        basicDataSource.setUrl(url);
        basicDataSource.setDriverClassName(dirverName);
        basicDataSource.setInitialSize(20);
    }

    //3、获得链接
    protected Connection getConnection(){
        try {
            connection = basicDataSource.getConnection();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return connection;
    }

    //4、得到预状态通道
    protected PreparedStatement getPps(String sql){
        try {
            pps = getConnection().prepareStatement(sql);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return pps;
    }

    //5、绑定参数 List保存的是给占位符所赋的值
    protected void param(List list){
        if(list!=null && list.size()>0){
            for (int i=0; i<list.size(); i++) {
                try {
                    pps.setObject(i+1, list.get(i));
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }

    //6、执行操作(增删改+查询)
    protected int update(String sql, List list){
        getPps(sql);
        param(list);

        try {
            count = pps.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return count;
    }

    //7、查询
    protected ResultSet query(String sql, List list){
        getPps(sql);
        param(list);
        try {
            resultSet = pps.executeQuery();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return resultSet;
    }

    //8、关闭资源
    protected void closeAll(){
        try {
            if (connection != null) {
                connection.close();
            }

            if (pps != null) {
                pps.close();
            }

            if (resultSet != null) {
                resultSet.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}

DBUtils_Druid

package util;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.commons.dbcp.BasicDataSource;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.ResourceBundle;

public class DBUtils_Druid {
    //1、定义变量
    private Connection connection;
    private PreparedStatement pps;
    private ResultSet resultSet;
    private int count;  //存储受影响的行数

    private static String dirverName;
    private static String username;
    private static String userpass;
    private static String url;

    private static DruidDataSource druidDataSource = new DruidDataSource();

    //2、加载驱动
    static {
        ResourceBundle bundle = ResourceBundle.getBundle("db");
        dirverName = bundle.getString("driverclass");
        url = bundle.getString("url");
        username = bundle.getString("uname");
        userpass = bundle.getString("upass");

        druidDataSource.setUsername(username);
        druidDataSource.setPassword(userpass);
        druidDataSource.setUrl(url);
        druidDataSource.setDriverClassName(dirverName);
        druidDataSource.setInitialSize(8);
    }

    //3、获得链接
    protected Connection getConnection(){
        try {
            connection = druidDataSource.getConnection();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return connection;
    }

    //4、得到预状态通道
    protected PreparedStatement getPps(String sql){
        try {
            pps = getConnection().prepareStatement(sql);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return pps;
    }

    //5、绑定参数 List保存的是给占位符所赋的值
    protected void param(List list){
        if(list!=null && list.size()>0){
            for (int i=0; i<list.size(); i++) {
                try {
                    pps.setObject(i+1, list.get(i));
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }

    //6、执行操作(增删改+查询)
    protected int update(String sql, List list){
        getPps(sql);
        param(list);

        try {
            count = pps.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return count;
    }

    //7、查询
    protected ResultSet query(String sql, List list){
        getPps(sql);
        param(list);
        try {
            resultSet = pps.executeQuery();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return resultSet;
    }

    //8、关闭资源
    protected void closeAll(){
        try {
            if (connection != null) {
                connection.close();
            }

            if (pps != null) {
                pps.close();
            }

            if (resultSet != null) {
                resultSet.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}

package test;

import bin.Student;
import dao.impl.TeacherDaoimpl;

import java.util.List;

public class Demo4 {

    public static void main(String[] args) {
        TeacherDaoimpl teacherDao = new TeacherDaoimpl();
        /*List<Student> allStudent = teacherDao.getAllStudent(Student.class);
        for (Student student : allStudent) {
            System.out.println(student.getStuId() + "," + student.getStuName()+","+student.getTeacherId());
        }*/

        Student byStuId = teacherDao.getByStuId(1);
        System.out.println(byStuId.getStuId()+","+byStuId.getStuName());
    }
}

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值