当前位置:网站首页>JDBC connection pool
JDBC connection pool
2022-07-01 06:06:00 【Fat man smiles】
Java Connection pools commonly used in are C3P0、DBCP、Druid etc. . We use Druid, benefits :
- Its help document is in Chinese , Easy to view
- It is a product after the use of a large amount of Alibaba data , It will work well
1, Add dependency
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.8</version>
</dependency>
2, Modify the connection database tool class
@Slf4j
public final class JdbcUtil {
// Define several parameters for connecting to the database
private static final String DRIVER;
private static final String URL;
private static final String USERNAME;
private static final String PASSWORD;
private JdbcUtil() {
}
// Load driver class , This loading operation can only be performed once in the project , No need to return to load
static {
try {
// Read db.properties The configuration file
InputStream is = JdbcUtil.class.getClassLoader().getResourceAsStream("db.properties");
Properties prop = new Properties();
prop.load(is);
DRIVER = prop.getProperty("jdbc.driver");
URL = prop.getProperty("jdbc.url");
USERNAME = prop.getProperty("jdbc.username");
PASSWORD = prop.getProperty("jdbc.password");
} catch (IOException e) {
log.info(" Error loading configuration file , The error message is :" + e.getMessage());
throw new RuntimeException(" Error loading configuration file , The error message is :" + e.getMessage());
}
}
/** * Get the connection object * @return Return connection object */
public static DataSource getDataSource() {
DruidDataSource ds = new DruidDataSource();
ds.setDriverClassName(DRIVER);
ds.setUrl(URL);
ds.setUsername(USERNAME);
ds.setPassword(PASSWORD);
return ds;
}
public static Connection getConnection() {
try {
return getDataSource().getConnection();
} catch (SQLException e) {
throw new RuntimeException(" Error creating connection object , The error message is :" + e.getMessage());
}
}
/** * General addition, deletion and modification methods of encapsulation * @param sql Operation required SQL sentence * @param params perform SQL Parameters required for statement */
public static int update(String sql, Object... params) {
Connection conn = null;
PreparedStatement pstm = null;
try {
// 2. Create connection objects
conn = getConnection();
// 3. Create execution SQL Statement object
pstm = conn.prepareStatement(sql);
// 4. Set parameters
for (int i = 0; i < params.length; i++) {
pstm.setObject(i + 1, params[i]);
}
// 5. perform SQL sentence
return pstm.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
return 0;
} finally {
// 6. Release resources
destroy(conn, pstm, null);
}
}
/** * Encapsulation method for querying multiple pieces of data * @param clazz The encapsulated object of the result * @param sql Executes SQL sentence * @param params perform SQL Parameters required for statement * @param <T> Generic types of consumer finance * @return Returns the result set of the query */
public static <T> List<T> query(Class<T> clazz, String sql, Object...params) {
Connection conn = null;
PreparedStatement pstm = null;
ResultSet rs = null;
List<T> entities = null;
try {
conn = getConnection();
pstm = conn.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
pstm.setObject(i + 1, params[i]);
}
rs = pstm.executeQuery();
entities = new ArrayList<>();
// obtain ResultSet Object to get metadata information
ResultSetMetaData metaData = rs.getMetaData();
// obtain SQL The number of fields in the language name
int columnCount = metaData.getColumnCount();
// Processing result set
while (rs.next()) {
// Instantiate objects through reflection
//T entity = clazz.newInstance();
T entity = clazz.getDeclaredConstructor().newInstance();
for (int i = 1; i <= columnCount; i++) {
// getColumnName() Is to get the field name in the table SELECT id,name,age FROM xxx
//metaData.getColumnName();
// getColumnLabel() Is to obtain SQL Field name in SELECT id,name as n,age FROM xxx
// Gets the name of the field
String columnLabel = metaData.getColumnLabel(i);
// Get the fields of the object through reflection
Field field = clazz.getDeclaredField(columnLabel);
// Set a value for this field
field.setAccessible(true);
field.set(entity, rs.getObject(columnLabel));
}
entities.add(entity);
}
return entities;
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(" Error querying multiple pieces of data , The error message is :" + e.getMessage());
} finally {
destroy(conn, pstm, rs);
}
}
/** * Encapsulation method for querying multiple pieces of data * @param clazz The encapsulated object of the result * @param sql Executes SQL sentence * @param params perform SQL Parameters required for statement * @param <T> Generic types of consumer finance * @return Return the result of the query */
public static <T> T queryForObject(Class<T> clazz, String sql, Object...params) {
Connection conn = null;
PreparedStatement pstm = null;
ResultSet rs = null;
T entity = null;
try {
conn = getConnection();
pstm = conn.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
pstm.setObject(i + 1, params[i]);
}
rs = pstm.executeQuery();
ResultSetMetaData metaData = rs.getMetaData();
while (rs.next()) {
if (clazz == Integer.class) {
Constructor<T> constructor = clazz.getDeclaredConstructor(int.class);
entity = constructor.newInstance(rs.getInt(1));
} else if (clazz == Long.class) {
Constructor<T> constructor = clazz.getDeclaredConstructor(long.class);
entity = constructor.newInstance(rs.getLong(1));
} else {
throw new RuntimeException(" Parameter can be transmitted int Type or long type .");
}
}
return entity;
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(" Error in statistics query , The error message is :" + e.getMessage());
} finally {
destroy(conn, pstm, rs);
}
}
/** * A common way to free up resources * @param conn Connection object * @param pstm Execute statement object * @param rs Result set object */
public static void destroy(Connection conn, PreparedStatement pstm, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
log.info(" Release ResultSet There was an error creating the object , The error message is :" + e.getMessage());
}
}
if (pstm != null) {
try {
pstm.close();
} catch (SQLException e) {
log.info(" Release PreparedStatement There was an error creating the object , The error message is :" + e.getMessage());
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
log.info(" Release Connection There was an error creating the object , The error message is :" + e.getMessage());
}
}
}
}
In this class , We added getDataSource() Method is used to create a connection pool object . And then in geConection() Method to get the connection object from the connection pool . In static code blocks The code to load the driver class is no longer required , Because this part of the function has been put into the connection pool object of .
3,ThreadLocal
JDK1.2 Has been provided in the version of ThreadLocal Object , It is produced to solve the concurrency problem of multithreaded programs .
This class provides the following static methods :
- get() : Used to get ThreadLocal The value of the shared variable for the current thread in .
- set(): Set up ThreadLocal The value of the variable shared by the current thread in .
- remove(): remove ThreadLocal The value of the variable shared by the current thread in .
- initialValue:ThreadLocal Calling the current thread when it is not assigned a value by the current thread remove Method and call get Method will return this value .
modify JdbcUtil This tool class , Let it support ThreadLocal
@Slf4j
public final class JdbcUtil {
// Data source connection pool object
private static DataSource dataSource;
// ThreadLocal object
private static ThreadLocal<Connection> threadLocal;
private JdbcUtil() {
}
// Load driver class , This loading operation can only be performed once in the project , No need to return to load
static {
try {
// Read db.properties The configuration file
InputStream is = JdbcUtil.class.getClassLoader().getResourceAsStream("db.properties");
Properties prop = new Properties();
prop.load(is);
// Use Druid Connection pool factory mode
dataSource = DruidDataSourceFactory.createDataSource(prop);
threadLocal = new ThreadLocal<>();
} catch (Exception e) {
log.info(" Error loading configuration file , The error message is :" + e.getMessage());
throw new RuntimeException(" Error loading configuration file , The error message is :" + e.getMessage());
}
}
/** * Get the connection object * @return Return connection object */
public static Connection getConnection() {
// Get connection from current thread
Connection conn = threadLocal.get();
if (conn == null) {
try {
// If not, you can get it from the connection pool
conn = dataSource.getConnection();
// Put it in ThreadLocal in
threadLocal.set(conn);
} catch (SQLException e) {
throw new RuntimeException(" Error creating connection object , The error message is :" + e.getMessage());
}
}
return conn;
}
/** * General addition, deletion and modification methods of encapsulation * @param sql Operation required SQL sentence * @param params perform SQL Parameters required for statement */
public static int update(String sql, Object... params) {
Connection conn = null;
PreparedStatement pstm = null;
try {
// 2. Create connection objects
conn = getConnection();
// 3. Create execution SQL Statement object
pstm = conn.prepareStatement(sql);
// 4. Set parameters
for (int i = 0; i < params.length; i++) {
pstm.setObject(i + 1, params[i]);
}
// 5. perform SQL sentence
return pstm.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
return 0;
} finally {
// 6. Release resources
destroy(conn, pstm, null);
}
}
/** * Encapsulation method for querying multiple pieces of data * @param clazz The encapsulated object of the result * @param sql Executes SQL sentence * @param params perform SQL Parameters required for statement * @param <T> Generic types of consumer finance * @return Returns the result set of the query */
public static <T> List<T> query(Class<T> clazz, String sql, Object...params) {
Connection conn = null;
PreparedStatement pstm = null;
ResultSet rs = null;
List<T> entities = null;
try {
conn = getConnection();
pstm = conn.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
pstm.setObject(i + 1, params[i]);
}
rs = pstm.executeQuery();
entities = new ArrayList<>();
// obtain ResultSet Object to get metadata information
ResultSetMetaData metaData = rs.getMetaData();
// obtain SQL The number of fields in the language name
int columnCount = metaData.getColumnCount();
// Processing result set
while (rs.next()) {
// Instantiate objects through reflection
//T entity = clazz.newInstance();
T entity = clazz.getDeclaredConstructor().newInstance();
for (int i = 1; i <= columnCount; i++) {
// getColumnName() Is to get the field name in the table SELECT id,name,age FROM xxx
//metaData.getColumnName();
// getColumnLabel() Is to obtain SQL Field name in SELECT id,name as n,age FROM xxx
// Gets the name of the field
String columnLabel = metaData.getColumnLabel(i);
// Get the fields of the object through reflection
Field field = clazz.getDeclaredField(columnLabel);
// Set a value for this field
field.setAccessible(true);
field.set(entity, rs.getObject(columnLabel));
}
entities.add(entity);
}
return entities;
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(" Error querying multiple pieces of data , The error message is :" + e.getMessage());
} finally {
destroy(conn, pstm, rs);
}
}
/** * Encapsulation method for querying multiple pieces of data * @param clazz The encapsulated object of the result * @param sql Executes SQL sentence * @param params perform SQL Parameters required for statement * @param <T> Generic types of consumer finance * @return Return the result of the query */
public static <T> T queryForObject(Class<T> clazz, String sql, Object...params) {
Connection conn = null;
PreparedStatement pstm = null;
ResultSet rs = null;
T entity = null;
try {
conn = getConnection();
pstm = conn.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
pstm.setObject(i + 1, params[i]);
}
rs = pstm.executeQuery();
ResultSetMetaData metaData = rs.getMetaData();
while (rs.next()) {
if (clazz == Integer.class) {
Constructor<T> constructor = clazz.getDeclaredConstructor(int.class);
entity = constructor.newInstance(rs.getInt(1));
} else if (clazz == Long.class) {
Constructor<T> constructor = clazz.getDeclaredConstructor(long.class);
entity = constructor.newInstance(rs.getLong(1));
} else {
throw new RuntimeException(" Parameter can be transmitted int Type or long type .");
}
}
return entity;
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(" Error in statistics query , The error message is :" + e.getMessage());
} finally {
destroy(conn, pstm, rs);
}
}
/** * A common way to free up resources * @param conn Connection object * @param pstm Execute statement object * @param rs Result set object */
public static void destroy(Connection conn, PreparedStatement pstm, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
log.info(" Release ResultSet There was an error creating the object , The error message is :" + e.getMessage());
}
}
if (pstm != null) {
try {
pstm.close();
} catch (SQLException e) {
log.info(" Release PreparedStatement There was an error creating the object , The error message is :" + e.getMessage());
}
}
if (conn != null) {
try {
conn.close();
// from ThreadLocal Delete the current connection object
threadLocal.remove();
} catch (SQLException e) {
log.info(" Release Connection There was an error creating the object , The error message is :" + e.getMessage());
}
}
}
}
边栏推荐
- FPGA - 7系列 FPGA内部结构之Clocking -01- 时钟架构概述
- SOE spatial analysis server MySQL and PostGIS geospatial database of Postgres anti injection attack
- Advanced drawing skills of Excel lecture 100 (1) - use Gantt chart to show the progress of the project
- C language beginner level - realize the minesweeping game
- How does MySQL store Emoji?
- Cjc8988 Low Power Stereo codec with 2 stereo headphone drivers
- SystemVerilog学习-06-类的封装
- Chip, an empire built on sand!
- srpingboot security demo
- Crossing sect · paipan + Siyuan notes = private notebook
猜你喜欢

excel動態圖錶

亲爱的派盘用户,我要向您表白!

论文学习记录随笔 多标签之GLOCAL

Index method and random forest to realize the information of surface water body in wet season in Shandong Province

FPGA - 7系列 FPGA内部结构之Clocking -01- 时钟架构概述

Crossing pie · pie pan + Mountain duck = local data management

excel初级应用案例——杜邦分析仪

three. JS summary

SystemVerilog学习-10-验证量化和覆盖率

让厦门灌口镇田头村变甜头村的特色农产品之一是蚂蚁新村
随机推荐
OpenGL ES: (5) OpenGL的基本概念、OpenGL ES 在屏幕产生图片的过程、OpenGL管线(pipeline)
Infinite horizontal marble game
excel动态图表
Beauty of Mathematics - Application of Mathematics
Seven major technical updates that developers should pay most attention to on build 2022
云盘里资料被和谐了,怎么办?
OpenGL es: (3) EGL, basic steps of EGL drawing, eglsurface, anativewindow
c# Xml帮助类
千万不要把笔记视频乱放!
OpenGL es: (4) detailed explanation of EGL API (Continued)
穿越派·派盘 + Mountain Duck = 数据本地管理
Dear pie users, I want to confess to you!
This is the necessary software for college students 𞓜 knowledge management
Smartinstantiationawarebeanpostprocessor of the extension point series determines which construction method to execute - Chapter 432
Small guide for rapid completion of mechanical arm (VI): stepping motor driver
Servlet
68 cesium code datasource loading czml
OpenGL es: (2) relationship between OpenGL es, EGL and glsl
Timer based on LabVIEW
栈题目:解析布尔表达式