当前位置:网站首页>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();
}
}
}
}
边栏推荐
- Handwriting blocking queue: condition + lock
- How can beginners learn flutter efficiently?
- Select drop-down box realizes three-level linkage of provinces and cities in China
- Array cyclic shift problem
- GPON other manufacturers' configuration process analysis
- Learn the memory management of JVM 02 - memory allocation of JVM
- Constructing expression binary tree with prefix expression
- Pytorch two-layer loop to realize the segmentation of large pictures
- Experimental design - using stack to realize calculator
- Basic operations of MySQL data table, addition, deletion and modification & DML
猜你喜欢

ZABBIX ODBC database monitoring

Resnet+attention project complete code learning

Pytoch loads the initialization V3 pre training model and reports an error

Tabbar configuration at the bottom of wechat applet

Course design of compilation principle --- formula calculator (a simple calculator with interface developed based on QT)

ZABBIX customized monitoring disk IO performance
Why do you always fail in automated tests?

Third party payment interface design

Yum only downloads the RPM package of the software to the specified directory without installing it

MySQL splits strings for conditional queries
随机推荐
Halcon template matching actual code (I)
Get the variable address of structure member in C language
July Huaqing learning-1
Yum only downloads the RPM package of the software to the specified directory without installing it
Intern position selection and simplified career development planning in Internet companies
One article tells the latest and complete learning materials of flutter
Solution to order timeout unpaid
II. Data type
Xi IO flow
Pytorch two-layer loop to realize the segmentation of large pictures
Seven ways to achieve vertical centering
Solve the problem of cache and database double write data consistency
IPv6与IPv4的区别 网信办等三部推进IPv6规模部署
Understand kotlin from the perspective of an architect
Seven polymorphisms
强化学习-学习笔记3 | 策略学习
Array cyclic shift problem
Pytoch monolayer bidirectional_ LSTM implements MNIST and fashionmnist data classification
ZABBIX ODBC database monitoring
POJ-2499 Binary Tree