Java JDBC (two) DAO mode

DAO mode

DAO mode introduction

Data Access Object (data access object)
is located between business logic and persistent data to
achieve access to persistent data

DAO functions as a converter, converting data between
entity classes and database records

The composition of the DAO model

Insert picture description here

Code implementation example:

1. Create a new BaseDAO interface

Set the name of the method that needs to be used first. The
code is as follows:

public interface BaseDAO {
    
    
    void getConn(String driver,String url,String user,String pwd);
    void query(String sql,String... params);
    boolean update(String sql,String... params);
    void close();
}

2. Create the implementation class BaseDAOImpl of the BaseDAO interface

The specific implementation of each method in the BaseDAO interface is perfected. The
code is as follows:

public class BaseDAOImpl implements BaseDAO {
    
    
    private Connection conn;
    private PreparedStatement pst;
    private ResultSet rs;

    public ResultSet getRs() {
    
    
        return rs;
    }

    @Override
    public void getConn(String driver, String url, String user, String pwd) {
    
    
        try {
    
    
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
    
    
            e.printStackTrace();
        }
        try {
    
    
            conn = DriverManager.getConnection(url,user,pwd);
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }
    }

    @Override
    public void query(String sql, String... params) {
    
    
        try {
    
    
            pst=conn.prepareStatement(sql);
            for (int i = 0; params!=null && i < params.length; i++) {
    
    
                pst.setObject(i+1,params[i]);
            }
            rs=pst.executeQuery();
        }
        catch (SQLException e) {
    
    
            e.printStackTrace();
        }


    }

    @Override
    public boolean update(String sql, String... params) {
    
    
        int num=0;
        try {
    
    
            pst=conn.prepareStatement(sql);
            for (int i = 0; params!=null && i < params.length; i++) {
    
    
                pst.setObject(i+1,params[i]);
            }
            num=pst.executeUpdate();
        }
        catch (SQLException e) {
    
    
            e.printStackTrace();
        }
        return num>0;
    }

    @Override
    public void close() {
    
    
        try {
    
    
            if (rs!=null)
            rs.close();
            if (pst!=null)
                pst.close();
            if (conn!=null)
                conn.close();
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }
    }
}

3. Create a new properties file

Create a new resources folder in the project, and create a new file named db.properties, and set it as a resource folder in the Project Structrue of idea (very important, you must not forget to set it!!!)
Insert picture description here
in the db.properties file Write keywords into it, corresponding to the contents of the mysql table set in advance

Insert picture description here

4. Create the Properties class

Create a Properties class method to read the content of the source file.
The advantage of using the static method is that the object can be generated first

public class Prop {
    
    
    static Properties p=new Properties();
    static {
    
    
        try {
    
    
            p.load(new FileInputStream("resources/db.properties"));
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
    }
    public static String getValue(String key){
    
    
       return p.getProperty(key);
    }
}

5. Create a student class

The
code used to store data is as follows:

public class Student {
    
    
    private int stu_id;
    private String stu_name;
    private int grade_id;
    private String gender;
    private String address;
    private String phone;
    private String idCard;

    @Override
    public String toString() {
    
    
        return "Student{" +
                "stu_id=" + stu_id +
                ", stu_name='" + stu_name + '\'' +
                ", grade_id=" + grade_id +
                ", gender='" + gender + '\'' +
                ", address='" + address + '\'' +
                ", phone='" + phone + '\'' +
                ", idCard='" + idCard + '\'' +
                '}';
    }

    public int getStu_id() {
    
    
        return stu_id;
    }

    public void setStu_id(int stu_id) {
    
    
        this.stu_id = stu_id;
    }

    public String getStu_name() {
    
    
        return stu_name;
    }

    public void setStu_name(String stu_name) {
    
    
        this.stu_name = stu_name;
    }

    public int getGrade_id() {
    
    
        return grade_id;
    }

    public void setGrade_id(int grade_id) {
    
    
        this.grade_id = grade_id;
    }

    public String getGender() {
    
    
        return gender;
    }

    public void setGender(String gender) {
    
    
        this.gender = gender;
    }

    public String getAddress() {
    
    
        return address;
    }

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

    public String getPhone() {
    
    
        return phone;
    }

    public void setPhone(String phone) {
    
    
        this.phone = phone;
    }

    public String getIdCard() {
    
    
        return idCard;
    }

    public void setIdCard(String idCard) {
    
    
        this.idCard = idCard;
    }
}

6. Create a studentDao class

As the main method, specifically implement the addition, deletion, modification, and query function of the database. The
specific code is as follows:

public class StudentDao extends BaseDAOImpl {
    
     //假装这里已经做了接口
    private final String Driver= Prop.getValue("driver");
    private final String url=Prop.getValue("url");
    private final String user=Prop.getValue("user");
    private final String pwd=Prop.getValue("pwd");
    //根据学生id查询所有信息
    public Student getStudentById(String id){
    
    
        String sql="select * from student where stu_id=?";
        getConn(Driver,url,user,pwd);
        query(sql,id);
        ResultSet rs=getRs();
        //Data Access Object
        Student s=new Student();
        try {
    
    
            if (rs.next()){
    
    
                s.setStu_id(rs.getInt("stu_id"));
                s.setStu_name(rs.getString("stu_name"));
                s.setGrade_id(rs.getInt("grade_id"));
                s.setGender(rs.getString("gender"));
                s.setAddress(rs.getString("address"));
                s.setPhone(rs.getString("phone"));
                s.setIdCard(rs.getString("idCard"));
            }
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }finally {
    
    
            close();
        }
        return s;
    }
    public void insertInto(String stu_id,String stu_name,String grade_id,String gender){
    
    
        String sql1="insert into student(stu_id,stu_name,grade_id,gender) values(?,?,?,?)";
        getConn(Driver,url,user,pwd);
        update(sql1,stu_id,stu_name,grade_id,gender);
    }

    public static void main(String[] args) {
    
    
        StudentDao dao=new StudentDao();
//        dao.insertInto("14","虚竹","3","男");
//        Student student=dao.getStudentById("14");
//        System.out.println(student);


        Student student1=dao.getStudentById("14");
        System.out.println(student1);
    }
}

7. Summary

The advantage of using the properties file is that it is flexible. When you need to change the database address or access multiple databases, you only need to modify the keywords in the properties file, which reduces the modification of the program code and makes the program more flexible and changeable.

Guess you like

Origin blog.csdn.net/giantleech/article/details/114539242