Java uses JDBC development to encapsulate its own JDBC CUtils tool class

Keywords: Database JDBC SQL MySQL

Catalog

I. Direct Encapsulation of JDBCUtils Tool Class

Encapsulation of JDBCUtils Tool Class with properties Profile

1. Use Properties Profile

2. Create configuration files

3. Loading configuration files

I. Direct Encapsulation of JDBCUtils Tool Class

In the development of JDBC, it is found that many codes are repetitive operations, such as "getting database connection" and "closing resources". Therefore, we can encapsulate our own tool class JDBCUtils to provide a method of getting object connection, so as to achieve code reuse.

Encapsulate your own tool class

public class JDBCUtils {
    private JDBCUtils() {

    }
    private static Connection con;
    //Define static code blocks, execute first
    static {
        try {
            //1. Register Driver Reflection Technology to Add Driver Class to Content
            Class.forName("com.mysql.jdbc.Driver");

            //2. Obtain the static method in the DriverManager class of database connection
            String url = "jdbc:mysql://localhost:3306/mydb";
            String username = "root";
            String password = "123456";
            con = DriverManager.getConnection(url, username, password);
        }catch (Exception ex){
            throw new RuntimeException(ex + "Failed to connect database!");
        }
    }

    //3. Define the static method and return the connection object of the database.
    public static Connection getConnertion(){
        return con;
    }

    //4. Release resources, because the release of resources will be different, we can use methods to overload.
    public static void close(Connection con, PreparedStatement pre){
        if(con != null){
            try{
                con.close();
            }catch(SQLException ex){}
        }

        if(pre != null){
            try{
                pre.close();
            }catch(SQLException ex){}
        }
    }
    //Release of resources (overload)
    public static void close(Connection con, PreparedStatement pre, ResultSet res){
        if(con != null){
            try{
                con.close();
            }catch(SQLException ex){}
        }

        if(pre != null){
            try{
                pre.close();
            }catch(SQLException ex){}
        }

        if(res != null){
            try{
                res.close();
            }catch(SQLException ex){}
        }
    }
}

Called in main

public static void main(String[] args) throws SQLException {
    //1. Get a database connection
    Connection con = JDBCUtils.getConnertion();
    String sql = "select * from student";

    //2. Getting preprocessed objects
    PreparedStatement pre = con.prepareStatement(sql);

    //3. Executing SQL statements
    ResultSet res = pre.executeQuery();
    while (res.next()){
        System.out.println(res.getString("sno") + "    " + res.getString("sname") + "    " +
                  res.getString("ssex") + "    " + res.getString("sage"));
    }

    //4. Releasing resources
    JDBCUtils.close(con,pre,res);
}

Encapsulation of JDBCUtils Tool Class with properties Profile

1. Use Properties Profile

In development, four parameters of connection are obtained: driver, URL, username and password. They are usually stored in configuration file for later maintenance. If the program needs to change the database, it only needs to change the configuration file. Usually, the following requirements are required for the configuration file:

  • File location: Suggested under src
  • File Name: Extended to properties
  • File content: A row of data in the form of "key=walue"
    (1) key: Name custom, if it is more than one word, it is customary to use point separation, such as: jdbc.driver
    (2) value: Value does not support Chinese. If non-English characters are needed, Unicode conversion will be performed.

2. Create configuration files

Create a database.properties file in the src directory, which reads as follows:

driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mydb
username=root
password=123456

3. Loading configuration files

  1. Load the database.properties configuration file
  2. Use IO to read files and store key-value pairs in Collections
  3. Get the connection information of the database from the collection in the way of key-value pairs to complete the connection of the database

Encapsulate your own tool class and load the configuration file

/**
 * Load the database.properties configuration file
 * Use IO to read files and store key-value pairs in Collections
 * Get the connection information of the database from the collection by key-value pairs to complete the connection of the database
 */
public class JDBCProUtlis {
    private JDBCProUtlis() {

    }
    private static Connection con;
    //Define static code blocks, execute first
    static {
        //Load the database.properties configuration file
        InputStream in = Main.class.getClassLoader().getResourceAsStream("database.properties");
        System.out.println(in);
        Properties pro = new Properties();
        try {
            pro.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //Use IO to read files and store key-value pairs in Collections
        String driverClass = pro.getProperty("driverClass");
        String url = pro.getProperty("url");
        String username = pro.getProperty("username");
        String password = pro.getProperty("password");

        try {
            //1. Register Driver Reflection Technology to Add Driver Class to Content
            Class.forName(driverClass);

            //2. Obtain the static method in the DriverManager class of database connection
            con = DriverManager.getConnection(url, username, password);
        }catch (Exception ex){
            throw new RuntimeException(ex + "Failed to connect database!");
        }
    }

    //3. Define the static method and return the connection object of the database.
    public static Connection getConnertion(){
        return con;
    }

    //4. Release resources, because the release of resources will be different, we can use methods to overload.
    public static void close(Connection con, PreparedStatement pre){
        if(con != null){
            try{
                con.close();
            }catch(SQLException ex){}
        }

        if(pre != null){
            try{
                pre.close();
            }catch(SQLException ex){}
        }
    }
    //Release of resources (overload)
    public static void close(Connection con, PreparedStatement pre, ResultSet res){
        if(con != null){
            try{
                con.close();
            }catch(SQLException ex){}
        }

        if(pre != null){
            try{
                pre.close();
            }catch(SQLException ex){}
        }

        if(res != null){
            try{
                res.close();
            }catch(SQLException ex){}
        }
    }
}

Called in main

public static void main(String[] args) throws SQLException {
    //1. Get a database connection
    Connection con = JDBCProUtlis.getConnertion();
    String sql = "select * from student";

    //2. Getting preprocessed objects
    PreparedStatement pre = con.prepareStatement(sql);

    //3. Executing SQL statements
    ResultSet res = pre.executeQuery();
    while (res.next()){
        System.out.println(res.getString("sno") + "    " + res.getString("sname") + "    " +
                res.getString("ssex") + "    " + res.getString("sage"));
    }

    //4. Releasing resources
    JDBCProUtlis.close(con,pre,res);
}

 

Posted by Shawazi on Thu, 01 Aug 2019 03:16:52 -0700