当前位置:网站首页>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();
}
}
}
}
边栏推荐
- ZABBIX ODBC database monitoring
- MySQL regular expression
- Resnet+attention project complete code learning
- PXE启动配置及原理
- ZABBIX agent2 monitors mongodb nodes, clusters and templates (official blog)
- Why do you always fail in automated tests?
- MySQL index - extended data
- Basic operations of MySQL data table, addition, deletion and modification & DML
- What is the difference between canvas and SVG?
- Tabbar configuration at the bottom of wechat applet
猜你喜欢
[superhard core] is the core technology of redis
How to clear floating?
Yum only downloads the RPM package of the software to the specified directory without installing it
Understand kotlin from the perspective of an architect
Get the variable address of structure member in C language
Resnet18 actual battle Baoke dream spirit
July Huaqing learning-1
MySQL splits strings for conditional queries
Summary of C language learning problems (VS)
Constructing expression binary tree with prefix expression
随机推荐
PXE startup configuration and principle
Conversion du format de données GPS [facile à comprendre]
Two minutes will take you to quickly master the project structure, resources, dependencies and localization of flutter
Matlab struct function (structure array)
Learn the memory management of JVM 03 - Method area and meta space of JVM
Understand redis persistence mechanism in one article
Seven polymorphisms
Pytoch loads the initialization V3 pre training model and reports an error
ZABBIX agent2 monitors mongodb nodes, clusters and templates (official blog)
Constructing expression binary tree with prefix expression
MySQL index - extended data
Solve the problem of cache and database double write data consistency
MVVM framework part I lifecycle
Learn garbage collection 01 of JVM -- garbage collection for the first time and life and death judgment
About cache exceptions: solutions for cache avalanche, breakdown, and penetration
ZABBIX agent2 monitors mongodb templates and configuration operations
图像超分实验:SRCNN/FSRCNN
A guide to threaded and asynchronous UI development in the "quick start fluent Development Series tutorials"
PIP command reports an error pip is configured with locations that requires tls/ssl problems
Learn JVM garbage collection 05 - root node enumeration, security points, and security zones (hotspot)