SoFunction
Updated on 2025-03-08

Detailed explanation of the code of BaseDao encapsulation, deletion, modification and search

1. What is BaseDao?

BaseDao is a common data access object used to provide basic operations on the database, such as inserting, updating, deleting and querying data. It usually encapsulates the underlying operations on the database, so that other DAO objects can inherit BaseDao to gain access to the database, while reducing duplicate code writing. BaseDao can provide basic CRUD (create, read, update, delete) functions, and can also implement some general query methods, such as conditional query, pagination query, etc. By using BaseDao, developers can operate databases more easily and improve development efficiency.

Advantages of BaseDao:

1. Code reuse

BaseDao provides a common database operation method, which can encapsulate some duplicate database operations, thereby reducing code redundancy.

2. Unified management

BaseDao can centrally manage database operations, and the database operation logic can be maintained and modified in a unified manner to improve the maintainability of the code.

3. Improve development efficiency

Using BaseDao can quickly complete database operations, reduce the time for developers to write duplicate code, and improve development efficiency.

4. Provide scalability

BaseDao can be expanded according to specific business needs, such as adding new query methods or custom database operation logic.

5. Reduce coupling

BaseDao can separate database operations from business logic, reduce coupling between modules, and improve system maintainability and testability.

To sum up, the use of BaseDao can simplify database operations and improve development efficiency and code quality.

2. What exactly does BaseDao do?

BaseDao is mainly responsible for obtaining data from the database and operating on data such as adding, deleting, modifying and checking tables in the database.

Specifically, BaseDao can do the following:

1. Add data: Add data to the database, including single data and batch data.

2. Modify data: Modify existing data in the database, and you can modify and update the data according to the specified conditions.

3. Delete data: Delete data in the database, and the data can be deleted according to the specified conditions.

4. Query data: Get data from the database, you can query according to specified conditions, or paging query.

In addition to the above basic operations, BaseDao can also provide some general query methods, such as query by condition, sort query, aggregation query, etc. to meet various business needs. By inheriting BaseDao, developers can reuse these basic operations, reduce duplicate code writing, and improve development efficiency.

3. BaseDao package addition, deletion, modification and search (detailed explanation of the code)

1) Basic JDBC operation class

  • Update operation (add, modify, delete)
    • 1. Add (add single data and batch data)
    • 2. Modify (modify existing data in the database, and you can modify and update the data according to the specified conditions)
    • 3. Delete (delete data in the database, and you can delete data according to the specified conditions)
  • Query operation
    • 1. Query a field (only one record will be returned and only one field; commonly used scenarios: query the total number)
    • 2. Query the collection

2) BaseDao package addition, deletion, modification and check

1. Connection: Connect the database to Java

/**
  * Database connection
  */
public class BaseDao {
    private String driver = "";// Database driver string    private String url = "jdbc:mysql://localhost:3306/epet";//Connect URL string    private String user = "root"; // Database username    private String password = "root"; // User password    Connection conn = null;				// Data connection object    /**
      * Get the database connection object
      */
    public Connection getConnection() {
        if(conn==null) {
            // Get the connection and catch the exception            try {
                (driver);
                conn = (url, user, password);
            } catch (Exception e) {
                ();// Exception handling            }
        }
        return conn;/ Return to the connection object
    }

2. Query: Query a field (return a record and only one field. Common scenarios: Query the number of fields)

/**
      * View operation
      * @param sql Precompiled SQL statements
      * @param objs string array
      * @return Return to view the number of rows of data
      *Query a field (only one record will be returned and only one field; commonly used scenarios: query the total number)
      * 1. Get the database connection
      * 2. Define SQL statements
      * 3. Pre-compiled
      * 4. If there are parameters, set the parameters, and the subscript starts from 1 (array or collection, loop setting parameters)
      * 5. Execute the query and return the result set
      * 6. Judgment and analyze the result set
      * 7. Close the resource
      */
    public ResultSet getCheckAll(String sql,Object [] objs){
        ResultSet rs=null;
        PreparedStatement pstmt = null;
        try {
            //Get the database connection            getConnection();
            //Define SQL statement            pstmt=(sql);
            //Precompiled            if(objs!=null){
                //If there are parameters, set the parameters, and the subscript starts from 1 (array or collection, loop setting parameters)                for (int i = 0; i <; i++) {
                    (i+1, objs[i]);
                }
            }
            //Execute the query and return the result set            rs=();
        } catch (SQLException e) {
            //throw an exception            ();
        } finally{
            //Close resources            closeAll(conn,pstmt,rs);
        }
        return rs;
    }

3. Add, delete and modify: add, delete and modify a field (return a record to be updated successfully!)

/**
      * Operations of adding, deleting, and modifying
      * @param preparedSql Precompiled SQL statements
      * @param Param String array
      * @return Number of rows affected
      * Add, delete, and modify a field (return to whether a record is updated successfully!)
      * 1. Get the database connection
      * 2. Define SQL statements
      * 3. Pre-compiled
      * 4. If there are parameters, set the parameters, and the subscript starts from 1 (array or collection, loop setting parameters)
      * 5. Execute addition, deletion, and modification, and return the result
      * 6. Judgment and analyze the results
      * 7. Close the resource
      */
    public int exceuteUpdate (String preparedSql, Object[] param) {
        PreparedStatement pstmt = null;
        int num = 0;
        //Get the database connection        conn =  getConnection();
        try {
            //Define SQL statement            pstmt = (preparedSql);
            if (param != null) {
                for (int i = 0; i < ; i++) {
                    //Set parameters for precompiled sql                    (i + 1, param[i]);
                }
            }
            //Execute addition, deletion, and modification, and return the result            num = ();
        } catch (SQLException e) {
            //Top sql type exception            ();
        } finally{
            //Close resources            closeAll(conn,pstmt,null);
        }
        return num;
    }

4. Close: determine whether the result set object is empty, and close it

/**
      * Close the database connection
      * @param conn Database connection
      * @param stmt Statement object
      * @param rs result set
      */
    public void closeAll(Connection conn, Statement stmt, ResultSet rs) {
        // If the result set object is not empty, close        if (rs != null) {
            try {
                ();
            } catch (Exception e) {
                ();
            }
        }
        // If the Statement object is not empty, close        if (stmt != null) {
            try {
                ();
            } catch (Exception e) {
                ();
            }
        }
        // If the database connection object is not empty, close        if (conn != null) {
            try {
                ();
            } catch (Exception e) {
                ();
            }
        }
    }

3) Demonstrate how to use BaseDao to add, delete, modify and check

The following code is to test BaseDao addition, deletion, modification and query, and demonstrate how BaseDao addition, deletion, modification and query are used.

package ;
/**
  * Test BaseDao adds, deletes, modify and check
  * Demonstrate how to use BaseDao to add, delete, modify and check
  * */
public class testDao {
    public static void main(String[] args) {
        /*Import BaseDao method*/
        BaseDao dao = new BaseDao();
 
        /*1. Test new functions*/
        //1.1. Pass in SQL statement 1.2. Pass in Object type object object        String sqlAdd = "insert into booksTab(id,name,author,price)VALUES(?,?,?,?)";
        Object[] objsAdd = {1001, "Java Begins to Jail", "Tang Moumou",158};
        //Return result        (sqlAdd, objsAdd);
 
        /*2. Test the delete function*/
        //2.1. Pass in SQL statement 2.2. Pass in Object type object object        String sqlDel = "delete booksTab where id = ?";
        Object[] objsDel = {1001};
        //Return result        (sqlDel, objsDel);
 
        /*3. Test modification function*/
        //3.1. Pass in SQL statement 3.2. Pass in Object type object object        String sqlUpdate = "update booksTab set name= ?,author = ?,price =? where id = ?";
        Object[] objsUpdate = {"Java Begins to Jail","Tang Moumou",158,1001};
        //Return result        (sqlUpdate, objsUpdate);
 
        /*4, Test viewing function*/
        //4.1. Pass in SQL statement 4.2. Pass in Object type object object        String sqlCheck = "select * from booksTab;";
        Object[] objsCheck = {};
        //Return result set        (sqlCheck, objsCheck);
    }
}

This is the article about the detailed explanation of the code of BaseDao encapsulation, deletion and retrieval. This is the end. For more related contents of BaseDao encapsulation, deletion and retrieval, please search for my previous articles or continue to browse the related articles below. I hope everyone will support me in the future!