当前位置:网站首页>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 .
边栏推荐
- Scalpel like analysis of JVM -- this article takes you to peek into the secrets of JVM
- Record the pit of NETCORE's memory surge
- [FPGA tutorial case 11] design and implementation of divider based on vivado core
- lora网关以太网传输
- Path of class file generated by idea compiling JSP page
- Exchange bottles (graph theory + thinking)
- KS003基于JSP和Servlet实现的商城系统
- After five years of testing in byte, I was ruthlessly dismissed in July, hoping to wake up my brother who was paddling
- MySQL transaction isolation level
- Interface idempotency
猜你喜欢
Basic knowledge of binary tree, BFC, DFS
关于进程、线程、协程、同步、异步、阻塞、非阻塞、并发、并行、串行的理解
C#(二十九)之C#listBox checkedlistbox imagelist
No qualifying bean of type ‘......‘ available
DM8 archive log file manual switching
Tips for using dm8huge table
Record the pit of NETCORE's memory surge
Viewing and verifying backup sets using dmrman
cookie,session,Token 这些你都知道吗?
Yyds dry goods inventory hcie security Day11: preliminary study of firewall dual machine hot standby and vgmp concepts
随机推荐
Custom event of C (31)
Global and Chinese markets for patent hole oval devices 2022-2028: Research Report on technology, participants, trends, market size and share
/usr/bin/gzip: 1: ELF: not found/usr/bin/gzip: 3: : not found/usr/bin/gzip: 4: Syntax error:
Error 1045 (28000): access denied for user 'root' @ 'localhost' (using password: no/yes
STC8H开发(十二): I2C驱动AT24C08,AT24C32系列EEPROM存储
Pandora IOT development board learning (HAL Library) - Experiment 9 PWM output experiment (learning notes)
Python book learning notes - Chapter 09 section 01 create and use classes
Brief tutorial for soft exam system architecture designer | general catalog
Prime Protocol宣布在Moonbeam上的跨链互连应用程序
2/13 qaq~~ greed + binary prefix sum + number theory (find the greatest common factor of multiple numbers)
Path of class file generated by idea compiling JSP page
Global and Chinese markets for otolaryngology devices 2022-2028: Research Report on technology, participants, trends, market size and share
JVM的手术刀式剖析——一文带你窥探JVM的秘密
绑定在游戏对象上的脚本的执行顺序
Conditionally [jsonignore]
Scalpel like analysis of JVM -- this article takes you to peek into the secrets of JVM
Unity中几个重要类
SSTI template injection explanation and real problem practice
Cf464e the classic problem [shortest path, chairman tree]
判断当天是当月的第几周