当前位置:网站首页>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 .
边栏推荐
猜你喜欢
Class A, B, C networks and subnet masks in IPv4
Security xxE vulnerability recurrence (XXe Lab)
[FPGA tutorial case 11] design and implementation of divider based on vivado core
绑定在游戏对象上的脚本的执行顺序
Record the pit of NETCORE's memory surge
Path of class file generated by idea compiling JSP page
C language -- structs, unions, enumerations, and custom types
WPF effect Article 191 box selection listbox
mysql关于自增长增长问题
lora网关以太网传输
随机推荐
Determine which week of the month the day is
Take you to wechat applet development in 3 minutes
记一次excel XXE漏洞
MySQL transaction isolation level
Global and Chinese market of aircraft anti icing and rain protection systems 2022-2028: Research Report on technology, participants, trends, market size and share
Web components series (VII) -- life cycle of custom components
《2022年中国银行业RPA供应商实力矩阵分析》研究报告正式启动
10个 Istio 流量管理 最常用的例子,你知道几个?
Thread sleep, thread sleep application scenarios
【可调延时网络】基于FPGA的可调延时网络系统verilog开发
IDEA编译JSP页面生成的class文件路径
How to modify field constraints (type, default, null, etc.) in a table
Ethernet port &arm & MOS &push-pull open drain &up and down &high and low sides &time domain and frequency domain Fourier
Ks003 mall system based on JSP and Servlet
Exchange bottles (graph theory + thinking)
math_极限&微分&导数&微商/对数函数的导函数推导(导数定义极限法)/指数函数求导公式推导(反函数求导法则/对数求导法)
Global and Chinese markets for medical gas manifolds 2022-2028: Research Report on technology, participants, trends, market size and share
mysql关于自增长增长问题
STC8H开发(十二): I2C驱动AT24C08,AT24C32系列EEPROM存储
Facebook and other large companies have leaked more than one billion user data, and it is time to pay attention to did