Java Web-JDBC-2-Not just Connections

Posted by new2code on Fri, 07 Jun 2019 22:31:32 +0200

Words
In Java Web-JDBC-1-not just the connection, we did the CURD operation, but we wrote it many times and thought about how to optimize it. Does that happen every time? This can only be regarded as an operator, an operator without thought.

Today, optimize on the basis of last time.
First look at the Java Web architecture:

First, the first version we upgraded today is daov 1.

It is found that in 1, the code is the same in loading drivers, getting connections, and closing resources, so it is encapsulated. Encapsulated as BaseDaoV1, the code is as follows:

package com.hmc.jdbc.daov1;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @Author Meice
 * @Date 2017 5 August 2000
 */
public class BaseDaoV1 {
    // Place the load driver part in the static statement block and load it as the class loads.
    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    //Encapsulate the operations common to all CURD s to the getConn() method.
    public Connection getConn() {
        Connection conn = null;
        String url = "jdbc:mysql://localhost:3306/news_db";
        String user = "root";
        String password = "119913";
        try {
            conn = DriverManager.getConnection(url, user, password);

        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return conn;
    }
    // Define the close() method for closing resources
    public void close(ResultSet rs, PreparedStatement ps, Connection conn) {
        try {
            if(rs != null) rs.close();
            if(ps != null) ps.close();
            if(conn != null) conn.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

Summary:

1 Repetitive code is encapsulated into a method and called directly. Like the one we set for ourselves
Some principles are the same as the bottom line. When we encounter similar things, we can choose them directly without entanglement. I will
Fixed to buy some brand clothes, buy directly when buying, very labor-saving, choice is very elaborate.
Force matters.
2 When creating a method, consider whether there is a return value, method modifier, and whether there are parameters.
3 We have four choices to make use of existing methods
1) new class, call method;
2) Set it as a static statement block, and load it directly with class loading without troop deployment.
3) This method is also defined as static, no new, direct call.
4) The class extends inherits the methods and attributes of the class (except private) and is called with this.

2. Test Edition, Test CURD

package com.hmc.jdbc.daov1;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @Author Meice
 * @Date 2017 5 August 2000
 */
public class TestBaseDaoV1CURD extends BaseDaoV1{
    //It is defined as a global variable to facilitate multiple method calls.
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    // 1 Test Select
    public void select() {
        //Call the encapsulated getConn() method of BaseDaoV1 to get the connection
        conn = this.getConn();
        String sql = "select * from t_news";
        // precompile
        try {
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            //Traversal result set
            while(rs.next()) {
                //Specific values in the collection can be obtained from. getInt (int column nIndex) or. getInt (String column nLabel).
                System.out.println(rs.getInt("id")+"--"+rs.getString("title")+rs.getString("author"));
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            //Call the close() method of closing the resource
            this.close(rs, ps, conn);
        }

    }

    //2 Testing Insert 
    public void add() {
        conn = this.getConn();
        String sql = "insert into t_news (title,author) values (?,?)";
        try {
            ps = conn.prepareStatement(sql);
            ps.setString(1, "I am V1 News1 Added to Version 1");
            ps.setString(2, "admin3");
            int result = ps.executeUpdate();
            if(result>0) {
                System.out.println("Congratulations on the success of the news!");
            }else {
                System.out.println("Unfortunately, adding news failed!");
            }

        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            /**
             * Note here that our executeUpdate() method does not return the result set ResultSet.
             * So instead of null, don't close it if it doesn't.
             */
            this.close(null, ps, conn);
        }

    }
    // 3 test update
    public void update() {
        conn = this.getConn();
        String sql = "update t_news set  title = ?,author = ? where id = ? ";
        try {
            ps = conn.prepareStatement(sql);
            //This parameter. What is the first parameter for? The second parameter represents the value
            ps.setString(1, "I am DaoV1 Revised news");
            ps.setString(2, "admin5");
            ps.setInt(3, 6);

            int result = ps.executeUpdate();
            if(result>0) {
                System.out.println("DaoV1 Successful news revision!");
            }else {
                System.out.println("Regrettably, DaoV1 Failed to revise the news!");
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            this.close(null, ps, conn);
        }

    }

    //4 Test delete
    public void Del() {
        conn = this.getConn();
        String sql = "delete from t_news where id = ?";
        try {

            ps = conn.prepareStatement(sql);
            //Note the location of the parameters, which should be precompiled before execution. If you report NullPointException before precompiling
            ps.setInt(1, 6);
            int result = ps.executeUpdate();
            if(result>0) {
                System.out.println("DaoV1 Delete successfully! Congratulations!");
            } else {
                System.out.println("DaoV1 Failed to execute deletion! Make persistent efforts!");
            }

        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            this.close(null, ps, conn);
        }



    }


    public static void main(String[] args) {
    //  new TestBaseDaoV1CURD().select();
    //  new TestBaseDaoV1CURD().add();
    //  new TestBaseDaoV1CURD().update();
        new TestBaseDaoV1CURD().Del();
    }


}

summary
1 In addition to Select being different, we found or wrote a lot of repetitive code. How can we continue to optimize it?
2. Optimize insert update delete, how to optimize it? It seems that we can only think about sql and reference.
3 Here we will find a disadvantage of main method testing. I just want to execute one method, but main() is always executed from beginning to end. So the test has to be commented out. As a result, Junit test has been born in the world, which is the test of which item.

Predict what happens and listen to the next breakdown.

Topics: SQL Java JDBC MySQL