当前位置:网站首页>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 .
边栏推荐
- All codes of Tetris
- Flutter event distribution
- Li Kou - binary tree pruning
- 2022年中科磐云——服务器内部信息获取 解析flag
- In Net 6.0
- SSG framework Gatsby accesses the database and displays it on the page
- Replay the snake game with C language (II) end
- 万字详解“用知识图谱驱动企业业绩增长”
- Due to fierce competition in the new market, China Mobile was forced to launch a restrictive ultra-low price 5g package
- Data communication foundation - layer 2 switching principle
猜你喜欢

Sqoop【环境搭建 01】CentOS Linux release 7.5 安装配置 sqoop-1.4.7 解决警告并验证(附Sqoop1+Sqoop2最新版安装包+MySQL驱动包资源)

Learning about opencv (3)
![[MySQL database] a collection of basic MySQL operations - the basis of seeing (adding, deleting, modifying, and querying)](/img/a7/b3bb6f584dff0eb9b49e81e5b9dade.png)
[MySQL database] a collection of basic MySQL operations - the basis of seeing (adding, deleting, modifying, and querying)

Meeting OA project (III) -- my meeting (meeting seating and submission for approval)

Uniapp error 7 < Map >: marker ID should be a number

Azkaban【基础知识 01】核心概念+特点+Web界面+架构+Job类型(一篇即可入门Azkaban工作流调度系统)

Spolicy request case

30分钟彻底弄懂 synchronized 锁升级过程

数通基础-Telnet远程管理设备

Basic usage of protobuf
随机推荐
SSG framework Gatsby accesses the database and displays it on the page
protobuf的基本用法
[award-winning question] ask Judea pearl, the Turing prize winner and the father of Bayesian networks
新增市场竞争激烈,中国移动被迫推出限制性超低价5G套餐
Vectortilelayer replacement style
Nodejs service background execution (forever)
Solve proxyerror: CONDA cannot proceed due to an error in your proxy configuration
Uniapp "no mobile phone or simulator detected, please try again later" and uniapp custom components and communication
Necessary for beginners: debug breakpoint debugging skills in idea and common breakpoint skills
[Qualcomm][Network] qti服务分析
解释一下自动装箱和自动拆箱?
30 minutes to thoroughly understand the synchronized lock upgrade process
Getting started with SQL - combined tables
Meeting OA project (III) -- my meeting (meeting seating and submission for approval)
Write a script that can run in Bash / shell and PowerShell
SQL Server 2008 server engine failed to start?
30分钟彻底弄懂 synchronized 锁升级过程
JS table auto cycle scrolling, mouse move in pause
面试突击68:为什么 TCP 需要 3 次握手?
Sqoop【付诸实践 02】Sqoop1最新版 全库导入 + 数据过滤 + 字段类型支持 说明及举例代码(query参数及字段类型强制转换)