当前位置:网站首页>JDBC -- extract JDBC tool classes
JDBC -- extract JDBC tool classes
2022-07-05 12:33:00 【It Chunhe】
Catalog
1、 Extract the code to obtain the database connection object
2、 Extract the registration driver code
3、 Methods of extracting and closing resources
5、 Extract the configuration file
The use of jdbc The code repetition of adding, deleting, modifying and checking the database is relatively high , Extract the repeated code into a tool class for code reuse , Simplify coding
First, observe which code has high repeatability :

Next write Jdbcutil Tool class
1、 Extract the code to obtain the database connection object
First, we want to get the database connection object that encapsulates the database connection information through the tool class connection
So you need to be in JdbcUtil Write a method The return is connection

Pass in the database connection information through parameters :

2、 Extract the registration driver code
You need to register drivers , First think of using static Static code block Load static code blocks as classes load Register driver
So when we use jdbcUtil Class when loading JdbcUtil Class, the driver will be registered

3、 Methods of extracting and closing resources
Get the method of overload writing to close resources through method The parameters passed are different The methods called are different
/**
* Release resources
*
* @param stmt
* @param conn
*/
public static void close(Statement stmt, Connection conn) {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(PreparedStatement pstmt, Connection conn) {
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* Release resources
*
* @param stmt
* @param conn
*/
public static void close(ResultSet rs, Statement stmt, Connection conn) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(ResultSet rs, PreparedStatement stmt, Connection conn) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
4、 test

Inquire about
// jdbc Tool class test
public class JdbcUtilTest {
public static void main(String[] args) {
ResultSet resultSet = null;
Connection connection = null;
Statement statement = null;
try {
// 1、 Registration drive Get database connection object
connection = JdbcUtil.getConnection();
// 2、 Print connection object See if you can get the database connection object
// System.out.println(connection);
// Definition sql
String sql = "select * from person";
// Access to perform sql The object of
statement = connection.createStatement();
// perform sql The query
resultSet = statement.executeQuery(sql);
// Process query results
while (resultSet.next()) {
System.out.println(resultSet.getString("name") + "---" + resultSet.getString("email"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// Release resources Calling tool class close Method
JdbcUtil.close(resultSet,statement,connection);
}
}
}

But we found the database connection information such as driver url User passwords and other information are still with java Code coupling is dead ,
In the future, we need to modify the database information , For example, when connecting to another database, you need to find the java Code modification , Very not what we want .
So we need to extract the database connection information separately Form a configuration file
Continue to improve the tool class code
5、 Extract the configuration file
stay src So let's make a new one properties file Fill in the database connection information

modify JdbcUtil Code
Read configuration file

test :

6、 Complete tool class code
package com.zhou.utils;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
// This is a jdbc Tool class of
public class JdbcUtil {
private static String url;
private static String user;
private static String passwd;
private static String driver;
static {
try {
// 1、 establish properties Collection classes
Properties properties = new Properties();
// 2、 Load profile
InputStream resourceAsStream = JdbcUtil.class.getClassLoader().getResourceAsStream("db.properties");
properties.load(resourceAsStream);
url = properties.getProperty("url");
user = properties.getProperty("user");
passwd = properties.getProperty("password");
driver = properties.getProperty("driver");
// Registration drive
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Get database connection object
* @return Data connection objects
*/
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url,user,passwd);
}
/**
* Release resources
*
* @param stmt
* @param conn
*/
public static void close(Statement stmt, Connection conn) {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(PreparedStatement pstmt, Connection conn) {
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* Release resources
*
* @param stmt
* @param conn
*/
public static void close(ResultSet rs, Statement stmt, Connection conn) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(ResultSet rs, PreparedStatement stmt, Connection conn) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
边栏推荐
- Design of music box based on assembly language
- Intern position selection and simplified career development planning in Internet companies
- Understanding the architecture type of mobile CPU
- Constructing expression binary tree with prefix expression
- What is the difference between canvas and SVG?
- UNIX socket advanced learning diary - advanced i/o functions
- Embedded software architecture design - message interaction
- MySQL transaction
- MySQL index - extended data
- Principle and performance analysis of lepton lossless compression
猜你喜欢

什么是数字化存在?数字化转型要先从数字化存在开始

Pytoch uses torchnet Classerrormeter in meter

Understand kotlin from the perspective of an architect

强化学习-学习笔记3 | 策略学习

Master the new features of fluent 2.10

Seven ways to achieve vertical centering

Redis highly available sentinel cluster

Principle of universal gbase high availability synchronization tool in Nanjing University

Redis clean cache

Knowledge representation (KR)
随机推荐
Matlab superpixels function (2D super pixel over segmentation of image)
Detailed steps for upgrading window mysql5.5 to 5.7.36
Matlab label2idx function (convert the label matrix into a cell array with linear index)
ZABBIX monitors mongodb (template and deployment operations)
UNIX socket advanced learning diary -ipv4-ipv6 interoperability
Third party payment interface design
Complete activity switching according to sliding
ZABBIX monitors mongodb templates and configuration operations
7月华清学习-1
POJ-2499 Binary Tree
Learn JVM garbage collection 02 - a brief introduction to the reference and recycling method area
POJ-2499 Binary Tree
ZABBIX 5.0 - LNMP environment compilation and installation
Pytoch counts the number of the same elements in the tensor
mysql拆分字符串做条件查询
Yum only downloads the RPM package of the software to the specified directory without installing it
MySQL trigger
byte2String、string2Byte
GPS數據格式轉換[通俗易懂]
GPON other manufacturers' configuration process analysis