当前位置:网站首页>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 .
边栏推荐
- Detailed explanation of serialization and deserialization
- 【按键消抖】基于FPGA的按键消抖模块开发
- What is the difference between gateway address and IP address in tcp/ip protocol?
- How to modify field constraints (type, default, null, etc.) in a table
- Prime protocol announces cross chain interconnection applications on moonbeam
- How does technology have the ability to solve problems perfectly
- 【leetcode】1189. Maximum number of "balloons"
- Facebook and other large companies have leaked more than one billion user data, and it is time to pay attention to did
- Record an excel xxE vulnerability
- Ks008 SSM based press release system
猜你喜欢

Custom event of C (31)

Execution order of scripts bound to game objects

MySql数据库root账户无法远程登陆解决办法

Comprehensive ability evaluation system

Viewing and verifying backup sets using dmrman

10个 Istio 流量管理 最常用的例子,你知道几个?

C (XXIX) C listbox CheckedListBox Imagelist

【leetcode】1189. Maximum number of "balloons"

C#(二十八)之C#鼠标事件、键盘事件

简易博客系统
随机推荐
C language -- structs, unions, enumerations, and custom types
[adjustable delay network] development of FPGA based adjustable delay network system Verilog
WPF effect Article 191 box selection listbox
C (XXIX) C listbox CheckedListBox Imagelist
1291_Xshell日志中增加时间戳的功能
Do you know cookies, sessions, tokens?
In Net 6 CS more concise method
Esp32 (based on Arduino) connects the mqtt server of emqx to upload information and command control
自动化测试怎么规范部署?
How does technology have the ability to solve problems perfectly
Viewing and verifying backup sets using dmrman
MySQL transaction isolation level
[disassembly] a visual air fryer. By the way, analyze the internal circuit
Simple blog system
Record the pit of NETCORE's memory surge
User datagram protocol UDP
食品行业仓储条码管理系统解决方案
[PSO] Based on PSO particle swarm optimization, matlab simulation of the calculation of the lowest transportation cost of goods at material points, including transportation costs, agent conversion cos
判断当天是当月的第几周
Thread sleep, thread sleep application scenarios