当前位置:网站首页>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();
}
}
}
}
边栏推荐
- Introduction to GNN
- Deep discussion on the decoding of sent protocol
- Redis clean cache
- Tabbar configuration at the bottom of wechat applet
- 信息服务器怎么恢复,服务器数据恢复怎么弄[通俗易懂]
- GPON other manufacturers' configuration process analysis
- C language structure is initialized as a function parameter
- Flutter2 heavy release supports web and desktop applications
- Conversion du format de données GPS [facile à comprendre]
- Knowledge representation (KR)
猜你喜欢

How to clear floating?

MySQL transaction

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

Understand redis persistence mechanism in one article

UNIX socket advanced learning diary -ipv4-ipv6 interoperability

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

Storage Basics

Intern position selection and simplified career development planning in Internet companies

How can beginners learn flutter efficiently?
[email protected] (using password"/>Solve the error 1045 of Navicat creating local connection -access denied for user [email protected] (using password
随机推荐
Learn the garbage collector of JVM -- a brief introduction to Shenandoah collector
Take you two minutes to quickly master the route and navigation of flutter
Resnet+attention project complete code learning
What is the difference between canvas and SVG?
16 channel water lamp experiment based on Proteus (assembly language)
Knowledge representation (KR)
ZABBIX customized monitoring disk IO performance
Summary of C language learning problems (VS)
Redis highly available sentinel cluster
Third party payment interface design
Experimental design - using stack to realize calculator
Clear neo4j database data
POJ-2499 Binary Tree
Pytoch uses torchnet Classerrormeter in meter
[HDU 2096] 小明A+B
How can beginners learn flutter efficiently?
Get the variable address of structure member in C language
MySQL constraints
Error modulenotfounderror: no module named 'cv2 aruco‘
MySQL trigger