当前位置:网站首页>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 .
边栏推荐
- C#(三十)之C#comboBox ListView treeView
- [Zhao Yuqiang] deploy kubernetes cluster with binary package
- Simple blog system
- In Net 6 CS more concise method
- 登录mysql输入密码时报错,ERROR 1045 (28000): Access denied for user ‘root‘@‘localhost‘ (using password: NO/YES
- Ybtoj coloring plan [tree chain dissection, segment tree, tarjan]
- 潘多拉 IOT 开发板学习(HAL 库)—— 实验9 PWM输出实验(学习笔记)
- How to standardize the deployment of automated testing?
- math_极限&微分&导数&微商/对数函数的导函数推导(导数定义极限法)/指数函数求导公式推导(反函数求导法则/对数求导法)
- WPF effect Article 191 box selection listbox
猜你喜欢
Error 1045 (28000): access denied for user 'root' @ 'localhost' (using password: no/yes
KS003基于JSP和Servlet实现的商城系统
cookie,session,Token 这些你都知道吗?
Fundamentals of SQL database operation
No qualifying bean of type ‘......‘ available
What is the difference between gateway address and IP address in tcp/ip protocol?
10個 Istio 流量管理 最常用的例子,你知道幾個?
[Zhao Yuqiang] deploy kubernetes cluster with binary package
Chinese brand hybrid technology: there is no best technical route, only better products
SSTI template injection explanation and real problem practice
随机推荐
阿里测试师用UI自动化测试实现元素定位
[disassembly] a visual air fryer. By the way, analyze the internal circuit
C#(三十一)之自定义事件
Hashcode and equals
Database, relational database and NoSQL non relational database
Prime protocol announces cross chain interconnection applications on moonbeam
2/10 parallel search set +bfs+dfs+ shortest path +spfa queue optimization
MySQL master-slave replication
Use js to complete an LRU cache
KS008基于SSM的新闻发布系统
Record the pit of NETCORE's memory surge
Fundamentals of SQL database operation
记一次excel XXE漏洞
Global and Chinese markets for MRI safe implants 2022-2028: technology, participants, trends, market size and share Research Report
/usr/bin/gzip: 1: ELF: not found/usr/bin/gzip: 3: : not found/usr/bin/gzip: 4: Syntax error:
2/11 matrix fast power +dp+ bisection
KS003基于JSP和Servlet实现的商城系统
【PSO】基于PSO粒子群优化的物料点货物运输成本最低值计算matlab仿真,包括运输费用、代理人转换费用、运输方式转化费用和时间惩罚费用
Path of class file generated by idea compiling JSP page
asp. Core is compatible with both JWT authentication and cookies authentication