当前位置:网站首页>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());
}
}
}
}
边栏推荐
- 69 Cesium代码datasource加载geojson
- Geoffrey Hinton: my 50 years of in-depth study and Research on mental skills
- π盘,让您电脑变成个人的私有云
- Codeforces Round #803 (Div. 2)vp
- highmap gejson数据格式转换脚本
- DEV XPO对比之XAF BO
- OpenGL ES: (3) EGL、EGL绘图的基本步骤、EGLSurface、ANativeWindow
- three. JS summary
- Pit of kotlin bit operation (bytes[i] and 0xff error)
- srpingboot security demo
猜你喜欢

One of the characteristic agricultural products that make Tiantou village, Guankou Town, Xiamen into a "sweet" village is

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

freeswitch拨打分机号

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

Leetcode Max rectangle, Max square series 84 85. 221. 1277. 1725. (monotonic stack, dynamic programming)

蚂蚁新村田头村变甜头村 让厦门灌口镇田头村变甜头村的特色农产品之一是

OpenGL es: (3) EGL, basic steps of EGL drawing, eglsurface, anativewindow

Seven major technical updates that developers should pay most attention to on build 2022

Small guide for rapid completion of mechanical arm (VI): stepping motor driver

穿越派·派盘 + Mountain Duck = 数据本地管理
随机推荐
解决麒麟V10上传文件乱码问题
为了保护自己的数据,他奋斗了一天一夜
Orcle创建用户+角色
TIDB数据库特性总结
Arcserver password reset (account cannot be reset)
健康照明中应用的LED照明灯
Huluer app help
In win10 and win11, the scroll direction of Elan touch panel is reversed, and "double finger click to open the right-click menu" and "double finger scroll" are started“
highmap gejson数据格式转换脚本
This is the necessary software for college students 𞓜 knowledge management
Smartinstantiationawarebeanpostprocessor of the extension point series determines which construction method to execute - Chapter 432
Through cooperation with the University of international trade, we can increase efficiency for college students
OpenGL es: (4) detailed explanation of EGL API (Continued)
[note] e-commerce order data analysis practice
Beauty of Mathematics - Application of Mathematics
Seven major technical updates that developers should pay most attention to on build 2022
论文学习记录随笔 多标签之LIFT
MySQL中 in 和 exists 的区别
Ant new village is one of the special agricultural products that make Tiantou village in Guankou Town, Xiamen become Tiantou village
Advanced drawing skills of Excel lecture 100 (1) - use Gantt chart to show the progress of the project