当前位置:网站首页>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());
}
}
}
}
边栏推荐
- Debug details under pycharm
- Small guide for rapid completion of mechanical arm (VI): stepping motor driver
- 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“
- kotlin位运算的坑(bytes[i] and 0xff 报错)
- PLA不粘贴在床上:6个简单的解决方案
- FPGA - 7系列 FPGA内部结构之Clocking -02- 时钟布线资源
- three.js小结
- 69 cesium code datasource loading geojson
- It's not that you have a bad mind, but that you haven't found the right tool
- Timer based on LabVIEW
猜你喜欢

Database problems, how to optimize Oracle SQL query statements faster and more efficient

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

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

He struggled day and night to protect his data

three. JS summary

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

π盘,让您电脑变成个人的私有云

68 Cesium代码datasource加载czml

Call us special providers of personal cloud services for College Students
随机推荐
Chip, an empire built on sand!
Diagramme dynamique Excel
数据库er图组成要素
Pla ne colle pas sur le lit: 6 solutions simples
How does MySQL store Emoji?
Ant new village is one of the special agricultural products that make Tiantou village in Guankou Town, Xiamen become Tiantou village
Stack Title: parsing Boolean expressions
One of the characteristic agricultural products that make Tiantou village, Guankou Town, Xiamen into a "sweet" village is
Continue to learn MySQL
excel動態圖錶
穿越派 你的数据云行
OpenGL ES: (5) OpenGL的基本概念、OpenGL ES 在屏幕产生图片的过程、OpenGL管线(pipeline)
[note] e-commerce order data analysis practice
The row and column numbers of each pixel of multi-source grid data in the same area are the same, that is, the number of rows and columns are the same, and the pixel size is the same
关于一道01背包问题的·拓展题的思考
蚂蚁新村田头村变甜头村 让厦门灌口镇田头村变甜头村的特色农产品之一是
可动的机械挂钟
C XML help class
【笔记】电商订单数据分析实战
Preliminary level of C language -- selected good questions on niuke.com