使用JDBC连接数据库

连接数据库

  1. 注册驱动 https://mvnrepository.com/search?q=mysql 官网下载对应的版本
  2. 在目录当中新建一个文件夹 libs(便于自己找到-基本放在根路径下),把下载的放在libs里,添加为库
  3. DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver() ); 加cj不加cj不影响,只是加了不会出现警告
    • DriverManager 的作用
      • 管理 JDBC 驱动程序:注册、加载和卸载数据库驱动。
      • 建立数据库连接:根据 URL 和连接参数创建Connection对象。
      • 提供驱动程序信息:获取已注册的驱动列表和驱动元数据。
  4. 建立连接
    final String URL=“jdbc:mysql://localhost:3306/itjiazhong”;url格式:jdbc:子协议:子名称//主机名:端口/数据库名?属性=值&
    final String USERNAME=“root”;
    final String PASSWORD=“123456”;
    Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
    • Connection 类的作用
      • 建立数据库连接:通过 JDBC URL、用户名和密码连接到特定数据库。
      • 创建执行 SQL 的对象:生成Statement、PreparedStatement或CallableStatement实例。
      • 管理事务:控制事务的提交、回滚和隔离级别。
      • 获取数据库元数据:通过getMetaData()方法获取数据库信息。
  5. 创建执行sql语句
    Statement statement = connection.createStatement();
    • Statement类的主要作用是向数据库发送 SQL 语句并执行相应操作。它有三种不同的实现形式:
      • Statement:适用于执行不带参数的简单 SQL 语句。
      • PreparedStatement(继承自Statement):可执行预编译的 SQL 语句,防止SQL注入,常用于需要多次执行的参数化查询。
      • CallableStatement(继承自PreparedStatement):主要用于调用数据库中的存储过程。
  6. 组织并执行sql语句 增 删 改
    查(多行数据):
    final String sql = “select * from employees”;
    ResultSet resultSet = statement.executeQuery(sql);
    • ResultSet类用于存储数据库查询后返回的数据结果,它就像一个数据表,通过游标在数据行之间移动来访问不同的数据。
      • 常用方法:
        • 移动游标的方法:
          next():将游标移动到下一行。如果存在下一行,返回true,否则返回false。
          previous():将游标移动到上一行。
          first()、last():分别将游标移动到第一行和最后一行。
          beforeFirst()、afterLast():分别将游标移动到数据集的开头之前和结尾之后。
        • 获取列值的方法:
          getInt(String columnLabel):获取指定列名对应的整数值。
          getString(String columnLabel):获取指定列名对应的字符串值。
          getDouble(String columnLabel):获取指定列名对应的双精度浮点数值。
          getDate(String columnLabel):获取指定列名对应的日期值。
          还可以通过列索引来获取值,例如getInt(1)表示获取第一列的值。
          增删改(只改变一行):
          int row = statement.executeUpdate(sql);
        • 定义的row是为了把sql执行的结果保存,便于方法的返回
  7. 处理结果(查询出来到控制台上,要么就是更新成功)
    while (resultSet.next()) {
    System.out.println(
    resultSet.getObject(1) + “\t” +
    resultSet.getObject(2) + “\t” +
    resultSet.getObject(3) + “\t” +
    resultSet.getObject(4) + “\t” +
    );
    }
    • 其中resultSet.getObject(number)表示返回表中的第number列,从1开始
  8. 关闭资源
    resultSet.close();
    statement.close();
    connection.close();
    • 最好按顺序关闭

利用JDBC学生信息管理

  • 四个包:
    • pojo:定义要从数据库中拿出的数据存放到这个包的类中(定义属性时候,基本数据类型会有空指针的风险,所以需要转换为引用数据类型)
    • dao: 用于编写数据库接口信息
      • impl:用于实现dao的抽象方法
    • service:编写获取数据库信息之后的逻辑接口
      • 实现service接口的抽象方法
    • controller:控制层主要是把数据传送到控制台或前端
  • 调用关系:service调用dao,controller调用service

步骤

popj包:

  1. 从数据库中拿出的数据存放到这个
public class Student {
    //基本数据类型会有空指针的风险,所以需要转换为引用数据类型
    private Integer id;
    private String first_name;
    private String last_name;
    private String birth;

    public Student() {
    }

    public Student(Integer id, String first_name, String last_name, String birth) {
        this.id = id;
        this.first_name = first_name;
        this.last_name = last_name;
        this.birth = birth;
    }

    public Integer getId() {
        return id;
    }

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

    public String getFirst_name() {
        return first_name;
    }

    public void setFirst_name(String first_name) {
        this.first_name = first_name;
    }

    public String getLast_name() {
        return last_name;
    }

    public void setLast_name(String last_name) {
        this.last_name = last_name;
    }

    public String getBirth() {
        return birth;
    }

    public void setBirth(String birth) {
        this.birth = birth;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", first_name='" + first_name + '\'' +
                ", last_name='" + last_name + '\'' +
                ", birth='" + birth + '\'' +
                '}';
    }
}

dao包:

  1. 先在dao中创一个接口,用于定义需要实现从数据库取数据的抽象方法
public interface StudentDao {
    //查询所有的学生的信息
    ArrayList<Student> findAll();

    //条件查询,根据id获取学生信息
    Student findById(Integer id);

    //新增学生信息
    int insert(Student stu);

    //修改学生信息
    int update(Student stu);

    //删除学生信息
    int delete(Integer id);

}
  1. 在dao中建一个实现dao抽象方法的类[注释部分未用到自己封装的工具类]

public class StudentDaoImpl implements StudentDao {
   /* @Override
    public ArrayList<Student> findAll() {
        ArrayList<Student> arrayList = new ArrayList<>();
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;

        try {
            DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/itjiazhong", "root", "123456");
            statement = connection.createStatement();
            String sql = "select * from my_table";
            resultSet = statement.executeQuery(sql);

            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String first_name = resultSet.getString("first_name");
                String last_name = resultSet.getString("last_name");
                String birthday = resultSet.getString("birth");
                Student student = new Student(id, first_name, last_name, birthday);
                arrayList.add(student);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
                if (statement != null) {
                    try {
                        statement.close();
                    } catch (SQLException e) {
                        throw new RuntimeException(e);
                    }
                }
                if (connection != null) {
                    try {
                        connection.close();
                    } catch (SQLException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
        return arrayList;
    }*/
   @Override
   public ArrayList<Student> findAll() {
       ArrayList<Student> arrayList = new ArrayList<>();
       Connection connection = null;
       Statement statement = null;
       ResultSet resultSet = null;

       try {

           connection = JDBCUtils.getConnection();
           statement = connection.createStatement();
           String sql = "select * from my_table";
           resultSet = statement.executeQuery(sql);

           while (resultSet.next()) {
               int id = resultSet.getInt("id");
               String first_name = resultSet.getString("first_name");
               String last_name = resultSet.getString("last_name");
               String birthday = resultSet.getString("birth");
               Student student = new Student(id, first_name, last_name, birthday);
               arrayList.add(student);
           }
       } catch (Exception e) {
           throw new RuntimeException(e);
       } finally {
           JDBCUtils.close(connection,statement,resultSet);
       }
       return arrayList;
   }
/*
    @Override
    public Student findById(Integer id) {
        Student student = new Student();
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;

        try {
            DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());
            //获取数据库的连接
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/itjiazhong", "root", "123456");
            //获取执行者对象
            statement = connection.createStatement();
            //编写sql语句并处理sql语句
            String sql = "select * from my_table where id = '" + id + "'";
            resultSet = statement.executeQuery(sql);
            //得到查询出来的结果集
            while (resultSet.next()) {
                Integer sid = resultSet.getInt("id");
                String first_name = resultSet.getString("first_name");
                String last_name = resultSet.getString("last_name");
                String birthday = resultSet.getString("birth");
                //封装成为一个student对象
                student.setId(sid);
                student.setFirst_name(first_name);
                student.setLast_name(last_name);
                student.setBirth(birthday);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        //返回集合的内容
        return student;
    }*/

    @Override
    public Student findById(Integer id) {
        Student student = new Student();
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;

        try {

            //获取数据库的连接
            connection = JDBCUtils.getConnection();
            //获取执行者对象
            statement = connection.createStatement();
            //编写sql语句并处理sql语句
            String sql = "select * from my_table where id = '" + id + "'";
            resultSet = statement.executeQuery(sql);
            //得到查询出来的结果集
            while (resultSet.next()) {
                Integer sid = resultSet.getInt("id");
                String first_name = resultSet.getString("first_name");
                String last_name = resultSet.getString("last_name");
                String birthday = resultSet.getString("birth");
                //封装成为一个student对象
                student.setId(sid);
                student.setFirst_name(first_name);
                student.setLast_name(last_name);
                student.setBirth(birthday);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
         JDBCUtils.close(connection,statement,resultSet);
        }
        //返回集合的内容
        return student;
    }
/*

    @Override
    public int insert(Student stu) {
        int row = 0;
        Connection connection = null;
        Statement statement = null;
        try {
            DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());
            //获取数据库的连接
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/itjiazhong", "root", "123456");
            //获取执行者对象
            statement = connection.createStatement();
            //编写sql语句并处理sql语句
            String sql = "INSERT INTO my_table (id, first_name, last_name, birth) VALUES ('" + stu.getId() + "', '" + stu.getFirst_name() + "', '" + stu.getLast_name() + "', '" + stu.getBirth() + "')";

            //得到查询出来的结果集
            row = statement.executeUpdate(sql);

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        //返回集合的内容
        return row;
    }
*/

    @Override
    public int insert(Student stu) {
        int row = 0;
        Connection connection = null;
        Statement statement = null;
        try {

            //获取数据库的连接
            connection = JDBCUtils.getConnection();
            //获取执行者对象
            statement = connection.createStatement();
            //编写sql语句并处理sql语句
            String sql = "INSERT INTO my_table (id, first_name, last_name, birth) VALUES ('" + stu.getId() + "', '" + stu.getFirst_name() + "', '" + stu.getLast_name() + "', '" + stu.getBirth() + "')";

            //得到查询出来的结果集
            row = statement.executeUpdate(sql);

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
         JDBCUtils.close(connection,statement);
        }
        //返回集合的内容
        return row;
    }
/*


    @Override
    public int update(Student stu) {
        int row = 0;
        Connection connection = null;
        Statement statement = null;
        try {
            DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());
            //获取数据库的连接
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/itjiazhong", "root", "123456");
            //获取执行者对象
            statement = connection.createStatement();
            //编写sql语句并处理sql语句
            String sql = "update my_table set id = '" + stu.getId() + "', first_name = '" + stu.getFirst_name() + "',last_name = '" + stu.getLast_name() + "',birth = '" + stu.getBirth() + "'  where id = '" + stu.getId() + "'";

            //得到查询出来的结果集
            row = statement.executeUpdate(sql);

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        //返回集合的内容
        return row;
    }
*/


    @Override
    public int update(Student stu) {
        int row = 0;
        Connection connection = null;
        Statement statement = null;
        try {
            //获取数据库的连接
            connection =JDBCUtils.getConnection();
            //获取执行者对象
            statement = connection.createStatement();
            //编写sql语句并处理sql语句
            String sql = "update my_table set id = '" + stu.getId() + "', first_name = '" + stu.getFirst_name() + "',last_name = '" + stu.getLast_name() + "',birth = '" + stu.getBirth() + "'  where id = '" + stu.getId() + "'";

            //得到查询出来的结果集
            row = statement.executeUpdate(sql);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
          JDBCUtils.close(connection,statement);
        }
        //返回集合的内容
        return row;
    }



   @Override
    public int delete(Integer id) {
        int row = 0;
        Connection connection = null;
        Statement statement = null;
        try {
            DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver() ); ;
            //获取数据库的连接
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/itjiazhong", "root", "123456");
            //获取执行者对象
            statement = connection.createStatement();
            //编写sql语句并处理sql语句
            String sql = "delete from my_table where id='" + id + "'";

            //得到查询出来的结果集
            row = statement.executeUpdate(sql);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭资源
           JDBCUtils.close(connection,statement);
        }
        //返回集合的内容
        return row;
    }

  /*  @Override
    public int delete(Integer id) {
        int row = 0;
        Connection connection = null;
        Statement statement = null;
        try {
            //获取数据库的连接
            connection = JDBCUtils.getConnection();
            //获取执行者对象
            statement = connection.createStatement();
            //编写sql语句并处理sql语句
            String sql = "delete from my_table where id='" + id + "'";

            //得到查询出来的结果集
            row = statement.executeUpdate(sql);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            JDBCUtils.close(connection,statement);
        }
        //返回集合的内容
        return row;
    }*/
}

service包:

  1. 编写获取数据库信息之后的逻辑接口
public interface StudentService {
        //查询所有的学生的信息
        ArrayList<Student> findAll();

        //条件查询,根据id获取学生信息
        Student findById(Integer id);

        //新增学生信息
        int insert(Student stu);

        //修改学生信息
        int update(Student stu);

        //删除学生信息
        int delete(Integer id);
}
  1. 实现获取数据库信息之后的逻辑方法

public class StudentServiceImpl implements StudentService {
    StudentDao studentDao=new StudentDaoImpl();
    @Override
    public ArrayList<Student> findAll() {
        return studentDao.findAll();
    }

    @Override
    public Student findById(Integer id) {
        return studentDao.findById(id);
    }

    @Override
    public int insert(Student stu) {
        return studentDao.insert(stu);
    }

    @Override
    public int update(Student stu) {
        return studentDao.update(stu);
    }

    @Override
    public int delete(Integer id) {
        return studentDao.delete(id);
    }
}

controller包:

  1. 调用方法输出结果
public class StudentController {
    StudentService studentService = new StudentServiceImpl();

    @Test
    public void findAll() {
        ArrayList<Student> students = studentService.findAll();
        for (Student student : students) {
            System.out.println(student);
        }
    }

    @Test
    public void findById() {
        Student student = studentService.findById(10001);
        System.out.println(student);
    }
    @Test
    public  void add(){
        Student student=new Student(1111,"huang","tianliang","M");
        studentService.insert(student);
    }

    @Test
    public void update() {
        Student student = studentService.findById(1111);
        student.setFirst_name("黄");
        int count = studentService.update(student);

        if (count != 0) {
            System.out.println("修改成功");
        } else {
            System.out.println("修改失败");
        }
    }

    @Test
    public void delete() {
        int count = studentService.delete(1111);
        if (count != 0) {
            System.out.println("删除成功");
        } else {
            System.out.println("删除失败");
        }

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值