📜  JDBC 使用模型对象和单例类

📅  最后修改于: 2021-09-10 02:41:23             🧑  作者: Mango

本文解释了如何使用来自 MySQL 数据库的Model对象和Singleton连接类来执行 JDBC 操作。

JDBC是Java的应用程序编程接口,它将Java应用程序与数据库连接起来以执行CRUD操作。

先决条件:

  • JDK 7+(点击此处下载)
  • MySQL 数据库(点击此处下载)
  • MySQL J 连接器(点击此处下载)
  • JDBC基础(点击这里学习JDBC)
  • Eclipse 或任何其他 IDE

模型类:模型类在 MVC 模式中被高度使用,它作为业务逻辑和视图之间的中间媒介。通常,模型包含特定实体的一些变量和方法。

单例类:单例类是一种软件设计模式,可确保该类只有一个实例。有多种方法可以实现单例类。

方法:我们将创建一个包含员工表的组织数据库。我们还将创建一个将与组织数据库连接的Java应用程序。连接将由包含所有必要驱动程序信息的单例类建立。在Java应用程序中,我们将使用 Employee 的模型对象执行一些数据操作任务,例如插入、删除、更新和检索。

  1. 创建 MySQL 数据库和表:
    create database org;
    use org;
    create table employee(
        emp_id int auto_increment,
        emp_name varchar(400),
        emp_address varchar(400),
        primary key (emp_id)
    );
    
  2. eclipse中的项目设置:
    • 在eclipse中创建一个名为’jdbc’的项目
    • 在该项目上创建一个名为“jars”的文件夹并将 MySQL J Connector 粘贴到该文件夹上
    • 将 jars 添加到Java构建路径
    • 创建 4 个包:com.jdbc.util、com.jdbc.dao、com.jdbc.model 和 com.jdbc.main

  3. 数据库连接:在com.jdbc.util包中创建单例连接类DatabaseConnection。在变量 user 上使用您的 MySQL 用户名和密码并通过。仔细查看“url”变量的最后一部分。必须保持名称与数据库名称相同。我的数据库的名称是“org”,这就是我将“org”放在 URL 变量中的原因。
    DatabaseConnection Class
    package com.jdbc.util;
      
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
      
    public class DatabaseConnection {
      
        private static Connection con = null;
      
        static
        {
            String url = "jdbc:mysql:// localhost:3306/org";
            String user = "root";
            String pass = "root";
            try {
                Class.forName("com.mysql.jdbc.Driver");
                con = DriverManager.getConnection(url, user, pass);
            }
            catch (ClassNotFoundException | SQLException e) {
                e.printStackTrace();
            }
        }
        public static Connection getConnection()
        {
            return con;
        }
    }


    Model Class
    package com.jdbc.model;
      
    public class Employee {
      
        int emp_id;
        String emp_name;
        String emp_address;
      
        public Employee() {}
      
        public Employee(String emp_name, String emp_address)
        {
            this.emp_name = emp_name;
            this.emp_address = emp_address;
        }
      
        public int getEmp_id()
        {
            return emp_id;
        }
      
        public void setEmp_id(int emp_id)
        {
            this.emp_id = emp_id;
        }
      
        public String getEmp_name()
        {
            return emp_name;
        }
      
        public void setEmp_name(String emp_name)
        {
            this.emp_name = emp_name;
        }
      
        public String getEmp_address()
        {
            return emp_address;
        }
      
        public void setEmp_address(String emp_address)
        {
            this.emp_address = emp_address;
        }
      
        @Override
        public String toString()
        {
            return "Employee [emp_id=" + emp_id + ", 
    emp_name=" + emp_name + ", 
    emp_address=" + emp_address + "]";
        }
    }


    EmployeeDao Interface
    package com.jdbc.dao;
      
    import java.sql.SQLException;
    import java.util.List;
      
    import com.jdbc.model.Employee;
      
    public interface EmployeeDao {
      
        public int add(Employee emp)
            throws SQLException;
        public void delete(int id)
            throws SQLException;
        public Employee getEmployee(int id)
            throws SQLException;
        public List getEmployees()
            throws SQLException;
        public void update(Employee emp)
            throws SQLException;
    }


    EmployeeDaoImplementation Class
    package com.jdbc.dao;
      
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.List;
      
    import com.jdbc.model.Employee;
    import com.jdbc.util.DatabaseConnection;
      
    public class EmployeeDaoImplementation
        implements EmployeeDao {
      
        static Connection con
            = DatabaseConnection.getConnection();
      
        @Override
        public int add(Employee emp)
            throws SQLException
        {
      
            String query
                = "insert into employee(emp_name, "
                  + "emp_address) VALUES (?, ?)";
            PreparedStatement ps
                = con.prepareStatement(query);
            ps.setString(1, emp.getEmp_name());
            ps.setString(2, emp.getEmp_address());
            int n = ps.executeUpdate();
            return n;
        }
      
        @Override
        public void delete(int id)
            throws SQLException
        {
            String query
                = "delete from employee where emp_id =?";
            PreparedStatement ps
                = con.prepareStatement(query);
            ps.setInt(1, id);
            ps.executeUpdate();
        }
      
        @Override
        public Employee getEmployee(int id)
            throws SQLException
        {
      
            String query
                = "select * from employee where emp_id= ?";
            PreparedStatement ps
                = con.prepareStatement(query);
      
            ps.setInt(1, id);
            Employee emp = new Employee();
            ResultSet rs = ps.executeQuery();
            boolean check = false;
      
            while (rs.next()) {
                check = true;
                emp.setEmp_id(rs.getInt("emp_id"));
                emp.setEmp_name(rs.getString("emp_name"));
                emp.setEmp_address(rs.getString("emp_address"));
            }
      
            if (check == true) {
                return emp;
            }
            else
                return null;
        }
      
        @Override
        public List getEmployees()
            throws SQLException
        {
            String query = "select * from employee";
            PreparedStatement ps
                = con.prepareStatement(query);
            ResultSet rs = ps.executeQuery();
            List ls = new ArrayList();
      
            while (rs.next()) {
                Employee emp = new Employee();
                emp.setEmp_id(rs.getInt("emp_id"));
                emp.setEmp_name(rs.getString("emp_name"));
                emp.setEmp_address(rs.getString("emp_address"));
                ls.add(emp);
            }
            return ls;
        }
      
        @Override
        public void update(Employee emp)
            throws SQLException
        {
      
            String query
                = "update employee set emp_name=?, "
                  + " emp_address= ? where emp_id = ?";
            PreparedStatement ps
                = con.prepareStatement(query);
            ps.setString(1, emp.getEmp_name());
            ps.setString(2, emp.getEmp_address());
            ps.setInt(3, emp.getEmp_id());
            ps.executeUpdate();
        }
    }


    Driver code
    package com.jdbc.main;
      
    import java.sql.SQLException;
    import java.util.List;
      
    import com.jdbc.dao.EmployeeDaoImplementation;
    import com.jdbc.model.Employee;
      
    public class Application {
      
        public static void main(String[] args)
            throws SQLException
        {
      
            Employee emp = new Employee();
            emp.setEmp_name("Haider");
            emp.setEmp_address("Mars");
            EmployeeDaoImplementation empDao
                = new EmployeeDaoImplementation();
      
            // add
            empDao.add(emp);
      
            // read
            Employee e = empDao.getEmployee(1);
            System.out.println(e.getEmp_id() + " "
                               + e.getEmp_name() + " "
                               + e.getEmp_address());
      
            // read All
            List ls = empDao.getEmployees();
            for (Employee allEmp : ls) {
                System.out.println(allEmp);
            }
      
            // update
            Employee tempEmployee = empDao.getEmployee(1);
            tempEmployee.setEmp_address("Asgard");
            empDao.update(tempEmployee);
      
            // delete
            empDao.delete(1);
        }
    }


  4. 模型类:在 com.jdbc.model 包中创建一个名为 Employee 的模型类。它应该包含所有属性作为变量。

    模型类

    package com.jdbc.model;
      
    public class Employee {
      
        int emp_id;
        String emp_name;
        String emp_address;
      
        public Employee() {}
      
        public Employee(String emp_name, String emp_address)
        {
            this.emp_name = emp_name;
            this.emp_address = emp_address;
        }
      
        public int getEmp_id()
        {
            return emp_id;
        }
      
        public void setEmp_id(int emp_id)
        {
            this.emp_id = emp_id;
        }
      
        public String getEmp_name()
        {
            return emp_name;
        }
      
        public void setEmp_name(String emp_name)
        {
            this.emp_name = emp_name;
        }
      
        public String getEmp_address()
        {
            return emp_address;
        }
      
        public void setEmp_address(String emp_address)
        {
            this.emp_address = emp_address;
        }
      
        @Override
        public String toString()
        {
            return "Employee [emp_id=" + emp_id + ", 
    emp_name=" + emp_name + ", 
    emp_address=" + emp_address + "]";
        }
    }
    
  5. 数据库访问对象(DAO):我们将创建一个 EmployeeDao 接口和另一个实现 EmployeeDao 的类 EmployeeDaoImplementation。这个实现的类将用作 DAO 来执行 CRUD 操作。我们将使用 PreparedStatement 来执行查询。 PreparedStatement 有 3 个特殊的方法:
    • executeQuery():用于检索数据
    • executeUpdate():用于插入、更新、删除
    • execute():用于创建

    EmployeeDao 接口

    package com.jdbc.dao;
      
    import java.sql.SQLException;
    import java.util.List;
      
    import com.jdbc.model.Employee;
      
    public interface EmployeeDao {
      
        public int add(Employee emp)
            throws SQLException;
        public void delete(int id)
            throws SQLException;
        public Employee getEmployee(int id)
            throws SQLException;
        public List getEmployees()
            throws SQLException;
        public void update(Employee emp)
            throws SQLException;
    }
    

    EmployeeDao实现类

    package com.jdbc.dao;
      
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.List;
      
    import com.jdbc.model.Employee;
    import com.jdbc.util.DatabaseConnection;
      
    public class EmployeeDaoImplementation
        implements EmployeeDao {
      
        static Connection con
            = DatabaseConnection.getConnection();
      
        @Override
        public int add(Employee emp)
            throws SQLException
        {
      
            String query
                = "insert into employee(emp_name, "
                  + "emp_address) VALUES (?, ?)";
            PreparedStatement ps
                = con.prepareStatement(query);
            ps.setString(1, emp.getEmp_name());
            ps.setString(2, emp.getEmp_address());
            int n = ps.executeUpdate();
            return n;
        }
      
        @Override
        public void delete(int id)
            throws SQLException
        {
            String query
                = "delete from employee where emp_id =?";
            PreparedStatement ps
                = con.prepareStatement(query);
            ps.setInt(1, id);
            ps.executeUpdate();
        }
      
        @Override
        public Employee getEmployee(int id)
            throws SQLException
        {
      
            String query
                = "select * from employee where emp_id= ?";
            PreparedStatement ps
                = con.prepareStatement(query);
      
            ps.setInt(1, id);
            Employee emp = new Employee();
            ResultSet rs = ps.executeQuery();
            boolean check = false;
      
            while (rs.next()) {
                check = true;
                emp.setEmp_id(rs.getInt("emp_id"));
                emp.setEmp_name(rs.getString("emp_name"));
                emp.setEmp_address(rs.getString("emp_address"));
            }
      
            if (check == true) {
                return emp;
            }
            else
                return null;
        }
      
        @Override
        public List getEmployees()
            throws SQLException
        {
            String query = "select * from employee";
            PreparedStatement ps
                = con.prepareStatement(query);
            ResultSet rs = ps.executeQuery();
            List ls = new ArrayList();
      
            while (rs.next()) {
                Employee emp = new Employee();
                emp.setEmp_id(rs.getInt("emp_id"));
                emp.setEmp_name(rs.getString("emp_name"));
                emp.setEmp_address(rs.getString("emp_address"));
                ls.add(emp);
            }
            return ls;
        }
      
        @Override
        public void update(Employee emp)
            throws SQLException
        {
      
            String query
                = "update employee set emp_name=?, "
                  + " emp_address= ? where emp_id = ?";
            PreparedStatement ps
                = con.prepareStatement(query);
            ps.setString(1, emp.getEmp_name());
            ps.setString(2, emp.getEmp_address());
            ps.setInt(3, emp.getEmp_id());
            ps.executeUpdate();
        }
    }
    
  6. 测试应用程序:最后,是时候使用 EmployeeDaoImplementation 的所有方法执行 CRUD 应用程序了。在 com.jdbc.main 包中创建一个类 Application。

    驱动程序代码

    package com.jdbc.main;
      
    import java.sql.SQLException;
    import java.util.List;
      
    import com.jdbc.dao.EmployeeDaoImplementation;
    import com.jdbc.model.Employee;
      
    public class Application {
      
        public static void main(String[] args)
            throws SQLException
        {
      
            Employee emp = new Employee();
            emp.setEmp_name("Haider");
            emp.setEmp_address("Mars");
            EmployeeDaoImplementation empDao
                = new EmployeeDaoImplementation();
      
            // add
            empDao.add(emp);
      
            // read
            Employee e = empDao.getEmployee(1);
            System.out.println(e.getEmp_id() + " "
                               + e.getEmp_name() + " "
                               + e.getEmp_address());
      
            // read All
            List ls = empDao.getEmployees();
            for (Employee allEmp : ls) {
                System.out.println(allEmp);
            }
      
            // update
            Employee tempEmployee = empDao.getEmployee(1);
            tempEmployee.setEmp_address("Asgard");
            empDao.update(tempEmployee);
      
            // delete
            empDao.delete(1);
        }
    }
    

输出:

  • 对于插入操作,您必须查看 Org 数据库中的 Employee 表。
  • 对于读取一项,使用 id 获取数据并将其打印到控制台。
  • 显示所有项目,只需调用该方法并将其打印到控制台。
  • 更新操作应该将更新的值更改到数据库中。
  • 删除操作将从数据库中删除该 id 的信息。