当前位置:网站首页>MySQL learning record 13 database connection pool, pooling technology, DBCP, c3p0
MySQL learning record 13 database connection pool, pooling technology, DBCP, c3p0
2022-07-06 04:07:00 【Jatine】
List of articles
MySQL Learning record 13 Database connection pool 、 Pool technology 、DBCP、C3P0
13.1 Database connection pool
13.1.1 Pool technology
In a nutshell , Is to save a lot of resources in advance , For a rainy day .
Due to our database connection → completion of enforcement → Releasing this process will waste system resources , Pooling technology prepares some resources in advance , Let the database connect to these resources prepared in advance .
for instance , Suppose the bank does not have pooling Technology , Every time I open the door , Serve only one person , Then close the door , Repeat the above steps for the next person . And if you have pooling Technology , There is a salesman waiting there after opening the door , Only the server is shut down , The salesman just went offline . How many salesmen are needed ? This is it. “ Minimum connections ”, Generally, it is the number of commonly used connections , The maximum number of connections is the maximum load limit of the service , Those who exceed the maximum number of connections can only queue .
Open source data source implementation ( Use immediately ):
- DBCP
- C3P0
- Druid: Alibaba
After using these database connection pools , We don't need to write the code to connect to the database in the project development
13.1.2DBCP
Needed jar package :commons-dbcp-1.4 、commons-pool-1.6
dbcpconfig.properties:
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=false
username=root
password=123456
#<!-- Initialize connection -->
initialSize=10
# Maximum number of connections
maxActive=50
#<!-- Maximum free connection -->
maxIdle=20
#<!-- Minimum free connection -->
minIdle=5
#<!-- Timeout wait time in milliseconds 6000 millisecond /1000 be equal to 60 second -->
maxWait=60000
#JDBC The format of the connection attribute attribute attached to the driver when establishing the connection must be as follows :【 Property name =property;】
# Be careful :"user" And "password" Two attributes are explicitly passed , So there's no need to include them .
connectionProperties=useUnicode=true;characterEncoding=UTF8
# Specifies the automatic commit of connections created by the connection pool (auto-commit) state .
defaultAutoCommit=true
#driver default Specifies the read-only... Of the connection created by the connection pool (read-only) state .
# If the value is not set , be “setReadOnly” Method will not be called .( Some drivers do not support read-only mode , Such as :Informix)
defaultReadOnly=
#driver default Specify the transaction level of the connection created by the connection pool (TransactionIsolation).
# The available values are one of the following :( Details visible javadoc.)NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE
defaultTransactionIsolation=READ_UNCOMMITTED
import org.apache.commons.dbcp.BasicDataSourceFactory;
import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class JdbcUtils_DBCP {
private static DataSource dataSource = null;
static {
try {
InputStream in = JdbcUtils_DBCP.class.getClassLoader().getResourceAsStream("dbcpconfig.properties");
Properties properties = new Properties();
properties.load(in);
// create data source Factory mode , Create objects
dataSource = BasicDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
// Get the connection
public static Connection getConnection() throws SQLException {
return dataSource.getConnection(); // Get the connection from the data source
}
// Release the connection
public static void release(Connection conn, Statement st, ResultSet rs) throws SQLException {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (conn != null) {
conn.close();
}
}
}
import java.sql.*;
public class TestDBCP {
public static void main(String[] args) throws SQLException {
Connection conn = null;
PreparedStatement st = null;
try {
conn = JdbcUtils_DBCP.getConnection(); // Get database connection , So it's connected , Don't write those configurations anymore
// difference Use ? Instead of parameters
String sql = "INSERT INTO users(id,`NAME`,`PASSWORD`,`email`,`birthday`)" + "VALUES(?,?,?,?,?)";
st = conn.prepareStatement(sql);// precompile sql, First write sql, Don't execute
// Assign parameters manually
st.setInt(1, 4);
st.setString(2, "haha");
st.setString(3, "123456");
st.setString(4, "[email protected]");
// Be careful sql.Date
// util.Date
st.setDate(5, new java.sql.Date(new java.util.Date().getTime()));
// perform
int i = st.executeUpdate(); // hold sql Statement is thrown in and executed ,i Is the number of rows affected
if (i > 0) {
System.out.println(" Insert the success !");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtils_DBCP.release(conn, st, null);
}
}
}
13.1.3C3P0
Needed jar package :c3p0-0.9.5.5 、mchange-commons-java-0.2.19
c3p0-config.xml:
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<!--
c3p0 Default ( Default ) To configure
If in code "ComboPooledDataSource ds=new ComboPooledDataSource();" This means that you are using c3p0 Default ( Default )
-->
<default-config>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&
useSSL=false
</property>
<property name="user">root</property>
<property name="password">123456</property>
<property name="acquiredIncrement">5</property>
<property name="initialPoolSize">10</property>
<property name="minPoolSize">5</property>
<property name="maxPoolSize">20</property>
</default-config>
<!--
c3p0 Named configuration for
If in code "ComboPooledDataSource ds=new ComboPooledDataSource("MySQL");" This means that you are using mysql Default ( Default )
-->
<named-config name="MySQL">
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=false&autoReconnect=true&failOverReadOnly=false
</property>
<property name="user">root</property>
<property name="password">123456</property>
<property name="acquiredIncrement">5</property>
<property name="initialPoolSize">10</property>
<property name="minPoolSize">5</property>
<property name="maxPoolSize">20</property>
</named-config>
</c3p0-config>
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;
import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class JdbcUtils_C3P0 {
private static ComboPooledDataSource dataSource = null;
static {
try {
// Code version configuration , Not recommended
// dataSource = new ComboPooledDataSource();
// dataSource.setDriverClass();
// dataSource.setUser();
// dataSource.setPassword();
// dataSource.setJdbcUrl();
//
// dataSource.setMaxPoolSize();
// create data source Factory mode , Create objects
dataSource = new ComboPooledDataSource("MySQL");// Configuration file writing
} catch (Exception e) {
e.printStackTrace();
}
}
// Get the connection
public static Connection getConnection() throws SQLException {
return dataSource.getConnection(); // Get the connection from the data source
}
// Release the connection
public static void release(Connection conn, Statement st, ResultSet rs) throws SQLException {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (conn != null) {
conn.close();
}
}
}
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class TestC3P0 {
public static void main(String[] args) throws SQLException {
Connection conn = null;
PreparedStatement st = null;
try {
conn = JdbcUtils_C3P0.getConnection();
// difference Use ? Instead of parameters
String sql = "INSERT INTO users(id,`NAME`,`PASSWORD`,`email`,`birthday`)" + "VALUES(?,?,?,?,?)";
st = conn.prepareStatement(sql);// precompile sql, First write sql, Don't execute
// Assign parameters manually
st.setInt(1, 5);
st.setString(2, "baba");
st.setString(3, "123456");
st.setString(4, "[email protected]");
// Be careful sql.Date
// util.Date
st.setDate(5, new Date(new java.util.Date().getTime()));
// perform
int i = st.executeUpdate(); // hold sql Statement is thrown in and executed ,i Is the number of rows affected
if (i > 0) {
System.out.println(" Insert the success !");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtils_C3P0.release(conn, st, null);
}
}
}
No matter what data source is used , The essence is the same ,DateSource The interface will not change , The method won't change .
边栏推荐
- Network security - Security Service Engineer - detailed summary of skill manual (it is recommended to learn and collect)
- 综合能力测评系统
- Redis (replicate dictionary server) cache
- [FPGA tutorial case 11] design and implementation of divider based on vivado core
- IDEA编译JSP页面生成的class文件路径
- Record the pit of NETCORE's memory surge
- Global and Chinese market of rubber wheel wedges 2022-2028: Research Report on technology, participants, trends, market size and share
- Brief tutorial for soft exam system architecture designer | general catalog
- Yyds dry goods inventory web components series (VII) -- life cycle of custom components
- Use js to complete an LRU cache
猜你喜欢
Le compte racine de la base de données MySQL ne peut pas se connecter à distance à la solution
简易博客系统
如何修改表中的字段约束条件(类型,default, null等)
C#(二十九)之C#listBox checkedlistbox imagelist
Security xxE vulnerability recurrence (XXe Lab)
DM8 archive log file manual switching
KS003基于JSP和Servlet实现的商城系统
Class A, B, C networks and subnet masks in IPv4
Redis (replicate dictionary server) cache
在 .NET 6 中使用 Startup.cs 更简洁的方法
随机推荐
math_ Derivative function derivation of limit & differential & derivative & derivative / logarithmic function (derivative definition limit method) / derivative formula derivation of exponential functi
Align items and align content in flex layout
Security xxE vulnerability recurrence (XXe Lab)
Use js to complete an LRU cache
C language -- structs, unions, enumerations, and custom types
Facebook等大厂超十亿用户数据遭泄露,早该关注DID了
Cf603e pastoral oddities [CDQ divide and conquer, revocable and search set]
Python book learning notes - Chapter 09 section 01 create and use classes
[FPGA tutorial case 11] design and implementation of divider based on vivado core
Basic knowledge of binary tree, BFC, DFS
关于进程、线程、协程、同步、异步、阻塞、非阻塞、并发、并行、串行的理解
Le compte racine de la base de données MySQL ne peut pas se connecter à distance à la solution
How to standardize the deployment of automated testing?
No qualifying bean of type ‘......‘ available
Cf464e the classic problem [shortest path, chairman tree]
The Research Report "2022 RPA supplier strength matrix analysis of China's banking industry" was officially launched
Determine which week of the month the day is
自动化测试的好处
《2022年中国银行业RPA供应商实力矩阵分析》研究报告正式启动
Plus d'un milliard d'utilisateurs de grandes entreprises comme Facebook ont été compromis, il est temps de se concentrer sur le did