For codes that can be reused, our best way is to encapsulate them and then call them directly the next time they are used. What I want to mention in this article is the JDBC tool class, which I believe everyone has come into contact with when learning Java. As for the method of encapsulating it, this article first briefly explains the tool class, lists the relevant encapsulation steps, and then brings relevant examples.
1. Description
In the process of Java development, some classes like Scanner and Random are often used in the code. They are classes for keyboard input and random number generation. Like a tool, they are called tool classes in Java.
2. Steps
Encapsulate JDBC tool class
Add a method to obtain the database connection object
Add a method to release the connection
3. Examples
package com.qianfeng.util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; /** * JDBC tool class * There is a way to get the connection * @author dushine */ public class JDBCUtil { /** * Method to obtain database connection * @return Connection conn * @throws SQLException */ public static Connection getConnection() throws SQLException { String url = "jdbc:mysql://localhost:3306/class?useSSL=false"; String user = "root"; String password = "root"; Connection conn = DriverManager.getConnection(url,user,password); return conn; } /** * Method to release connection * @param conn * @throws SQLException */ public static void releaseSourse(Connection conn) throws SQLException { if (conn != null) { conn.close(); } } /** * Method to release connection * @param conn database connection object * @param stmt The object to execute the SQL statement * @throws SQLException */ public static void releaseSourse(Connection conn,Statement stmt) throws SQLException { if (stmt != null) { stmt.close(); } if (conn != null) { conn.close(); } } /** * Method to release connection * @param conn database connection object * @param stmt The object to execute the SQL statement * @param resultSet The result set returned by executing the SQL statement * @throws SQLException */ public static void releaseSourse(Connection conn,Statement stmt,ResultSet resultSet) throws SQLException { if (resultSet != null) { resultSet.close(); } if (stmt != null) { stmt.close(); } if (conn != null) { conn.close(); } } }
The above is the method of encapsulating JDBC tool classes in Java. After reading the detailed explanation, you may wish to try the encapsulated code part yourself to see if you can complete the practical operation independently.