当前位置:网站首页>Self encapsulated database dbutils universal template
Self encapsulated database dbutils universal template
2022-07-26 10:13:00 【Yuyu fish】
List of articles
Preface
Many steps of database operation are repeated , It is not worth spending a lot of time and manpower to edit , So we can write a tool class by ourselves , When encapsulating several same methods of database operation , It's much more convenient to call directly . In short , To simplify the JDBC operation , Can write less code .
One 、 What are the main steps of encapsulating database operations ?
1. The import related jar package .
2. Create a profile , Go to the configuration file to edit the specific value of the database connection .
3. Write the loading and implementation configuration file in the tool class .
4. To realize the connection of database , close .
5. To implement transaction related operations , Open transaction , Commit transaction , Roll back the transaction .
Two 、 Use steps
1. Import and stock in
The code is as follows ( Example ):
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
2. Load configuration files and transaction information
The code is as follows ( Example ):
public class DbUtils {
private static DruidDataSource ds;
private static final ThreadLocal<Connection> THREAD_LOCAL = new ThreadLocal<>();
static {
Properties properties = new Properties();
InputStream is = DbUtils.class.getResourceAsStream("/database.properties");
try {
properties.load(is);
ds = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
3. The connection and closing methods of the database are encapsulated
// Database connection
public static Connection getConnection() {
Connection connection = THREAD_LOCAL.get();
try {
if (connection == null) {
connection = ds.getConnection();
THREAD_LOCAL.set(connection);
}
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
// Database shutdown
public static void closeAll(Connection connection, Statement statement, ResultSet resultSet) {
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
THREAD_LOCAL.remove();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
4. Operations related to database transactions
// The beginning of the business
public static void begin() {
Connection connection = null;
try {
connection = getConnection();
connection.setAutoCommit(false);
} catch (SQLException e) {
e.printStackTrace();
}
}
// Commit of transaction
public static void commit() {
Connection connection = null;
try {
connection = getConnection();
connection.commit();
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeAll(connection, null, null);
}
}
// Rollback of transaction
public static void rollback() {
Connection connection = null;
try {
connection = getConnection();
connection.rollback();
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeAll(connection, null, null);
}
}
5. Database connection configuration information
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/ems?useUnicode=true&characterEncoding=UTF-8
username=root
password=123456
# Initialize connection
initialSize=10
# Maximum number of connections
maxActive=30
# Minimum free connection
maxIdle=5
# Timeout waiting time
maxWait=3000
summary
If there are any mistakes , I hope you will point out that , Thank you for your care .
边栏推荐
- I finished watching this video on my knees at station B
- Force deduction DFS
- Meeting OA project (III) -- my meeting (meeting seating and submission for approval)
- Mysql5.7.25 master-slave replication (one-way)
- Tableviewcell highly adaptive
- Azkaban【基础知识 01】核心概念+特点+Web界面+架构+Job类型(一篇即可入门Azkaban工作流调度系统)
- 在.NET 6.0中配置WebHostBuilder
- Uniapp error 7 < Map >: marker ID should be a number
- SQL Server 2008 R2 installation problems
- Tower of Hanoi II | tower of Hanoi 4 columns
猜你喜欢

Flask框架初学-04-flask蓝图及代码抽离

Mysql5.7.25 master-slave replication (one-way)

【有奖提问】向图灵奖得主、贝叶斯网络之父 Judea Pearl 提问啦

挡不住了,纯国产PC已就位,美国的软硬件体系垄断正式被破

Production of a-modal drag function in antui

Unstoppable, pure domestic PCs have been in place, and the monopoly of the U.S. software and hardware system has been officially broken

AirTest

Leetcode 504. 七进制数

Session based recommendations with recurrent neural networks

Apple dominates, Samsung revives, and domestic mobile phones fail in the high-end market
随机推荐
Strange Towers of Hanoi|汉诺塔4柱问题
Study on the basis of opencv
Uniapp "no mobile phone or simulator detected, please try again later" and uniapp custom components and communication
Reproduce the snake game in C language (I) build pages and construct snakes
protobuf的基本用法
Solve proxyerror: CONDA cannot proceed due to an error in your proxy configuration
Wechat applet learning notes 1
Under win10 64 bit, matlab fails to configure notebook
AirTest
WARNING: [pool www] server reached pm. max_ children setting (5), consider raising it
[award-winning question] ask Judea pearl, the Turing prize winner and the father of Bayesian networks
spolicy请求案例
Distributed network communication framework: how to publish local services into RPC services
Like, "new programmer" e-book is free for a limited time!
Installation and use of cocoapods
IE7 set overflow attribute failure solution
Wechat applet development
解释一下自动装箱和自动拆箱?
Encapsulation of tabbarcontroller
PMM (percona monitoring and management) installation record