当前位置:网站首页>JDBC database connection pool
JDBC database connection pool
2022-07-23 11:09:00 【Purple green sword】
JDBC Database connection pool
1. Concept
It's actually a container ( aggregate ), Container for database connection .
- When the system is initialized , The container is created , Some database connection objects will be applied in the container , When the user comes to access the database , Get the connection object from the container , The user returns the connection to the container after accessing the database .
2. benefits
- Saving resource
- Efficient user access
2. Realization
2.1 Standard interface

- Standard interface :
DataSourcejava.sqlUnder bag - Method
- Get the connection :
getConnection() - Return connection :
Connection.close(). If Connection It's taken from the connection pool , that close() Method , Will not close the connection . But return the connection
- Get the connection :
2.2 C3P0 Database connection pool
1. rely on jar package
- Address connection :Mchange Commons Java,C3P0
2. Define configuration file
name :
c3p0.propertiesperhapsc3p0-config.xml<?xml version="1.0" encoding="UTF-8"?> <c3p0-config> <default-config> <!-- Connection parameter settings , Password and driver --> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql://127.0.0.1:3306/test?serverTimezone=UTC</property> <property name="user">root</property> <property name="password">root</property> <!-- Connection pool parameters --> <!-- Initial number of applications --> <property name="initialPoolSize">10</property> <!-- <property name="maxIdleTime">30</property>--> <!-- maximum connection --> <property name="maxPoolSize">100</property> <!-- <property name="minPoolSize">10</property>--> <!-- Set timeout --> <property name="checkoutTimeout">3000</property> </default-config> <named-config name="mySource"> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql://localhost:3306/bookstore</property> <property name="user">root</property> <property name="password">xxxx</property> <property name="initialPoolSize">10</property> <property name="maxIdleTime">30</property> <property name="maxPoolSize">100</property> <property name="minPoolSize">10</property> </named-config> </c3p0-config>route : Directly on
srcUnder the table of contents .
3. Create the core object and get the connection object
- Create objects
ComboPooledDataSource() - Get objects
ds.getConnection()
package com.sql.one;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
public class C3P0Demo {
public static void main(String[] args) throws SQLException {
// Create database connection pool object
DataSource ds=new ComboPooledDataSource();
// Get the connection object
Connection conn=ds.getConnection();
//3. Print connection
System.out.println(conn);
}
}

package com.sql.one;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
public class C3P0Demo {
public static void main(String[] args) throws SQLException {
// Create database connection pool object , Parameters can be passed in xml In the configuration file name Use other cheap
DataSource ds=new ComboPooledDataSource();
// Get the connection object
// Connection conn=ds.getConnection();
//3. Print connection
for(int i=1;i<=10;i++){
Connection conns=ds.getConnection();
System.out.println(i+":"+conns);
if(i==5){
conns.close();// Returning the connection is not closing
}
}
}
}

2.3 Druid Database connection pool
1. rely on jar package
Address :https://mvnrepository.com/artifact/com.alibaba/druid
2. Define configuration file
# Drive loading
driverClassName=com.mysql.jdbc.Driver
# Registration drive
url=jdbc:mysql://127.0.0.1:3306/test?serverTimezone=UTC
# user
username=root
# password
password=password123
# The number of physical connections established in the pool during initialization .
initialSize=2
# Maximum number of active connection pools
maxActive=50
# The maximum waiting time unit is milliseconds ,60*1000 =1 minute
maxWait=60000
- You can call it anything , It can be placed in any directory
3. Get database connection pool
adopt Factory To get DruidDataSourceFactory
package com.sql.one; import com.alibaba.druid.pool.DruidDataSourceFactory; import javax.sql.DataSource; import java.io.InputStream; import java.util.Properties; import java.sql.Connection; public class DruidDemo { public static void main(String[] args)throws Exception{ //1. Import jar package //2. Load profile Properties pro =new Properties(); InputStream is =DruidDemo.class.getClassLoader().getResourceAsStream("druid.properties"); pro.load(is); //4. Get connection pool object , Using factory mode DataSource ds= DruidDataSourceFactory.createDataSource(pro); //5. Get the connection Connection conn= ds.getConnection(); System.out.println(conn); } }
4. Get the connection

3. Encapsulation of tool class
3.1 summary
Define a class JDBCUtils
Provide static code block loading configuration file , Initialize connection pool object
Provide methods
- Get the connection method : Get the connection through the database connection pool
- Release resources
- How to get the connection pool
3.2 Test use
package com.sql.one;
import com.sql.jdbcutils.JDBCUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class DuridDemo2 {
public static void main(String[] args) {
try {
Connection conn= JDBCUtils.getConnection();
String sql="insert into t1 values(null,?,?)";
PreparedStatement pstmt= conn.prepareStatement(sql);
// to SQL Medium ? assignment
pstmt.setString(1," Logic ");
pstmt.setInt(2,30);
int count=pstmt.executeUpdate();
System.out.println(count);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}

4.Spring JDBC
4.1 summary

call JdbcTemplate To complete CRUD operation
update(): perform DML sentence . increase 、 Delete 、 Change statement .
queryForMap(): Query results , Encapsulate the result set as map aggregate
queryForList(): The query results are encapsulated as list aggregate
query(): The query result is returned as JavaBean object
queryForObject: Query results , Encapsulate the results as objects .
4.2 Easy to use
The import related
jarpackage
Easy to use , But the premise is to have a database connection pool
DataSourcepackage com.sql.jdbctemplate; import com.sql.jdbcutils.JDBCUtils; import org.springframework.jdbc.core.JdbcTemplate; public class JDBCTemplate { public static void main(String[] args) { //1. Import jar package //2. establish JDBCTemplate object JdbcTemplate template =new JdbcTemplate(JDBCUtils.getDataSource()); //3. Calling method String sqlstr="insert into t1 values(null,?,?)"; int count = template.update(sqlstr, " Shi Qiang ", 30); System.out.println(" Insert "+count+" Data succeeded "); } }
4.3 Simple use of test module
Annotate the function name
@Test, Then the modified function can be executed independently , Independent of the main method .
4.4 Introduction of common methods
1. update() Method
- Returns the number of entries inserted into the database .
package com.sql.jdbctemplate;
import com.sql.jdbcutils.JDBCUtils;
import org.testng.annotations.Test;
import org.springframework.jdbc.core.JdbcTemplate;
public class JdbcTemplateDemo2 {
// Instantiation JdbcTemplate
JdbcTemplate template= new JdbcTemplate(JDBCUtils.getDataSource());
//Junit unit testing , The method can be executed independently , Use @Test annotation ,
@Test
public void test1(){
String sqlstr="insert into t1 values(null,?,?)";
int count = template.update(sqlstr, " AI AA", 30);
System.out.println(" Insert "+count+" Data succeeded ");
//System.out.println(" I was executed ");
}
}

2. queryForMap () Method
return map aggregate , There can only be one result .
@Test public void test2(){ String sqlstr="select * from t1 where id=1"; Map<String, Object> map = template.queryForMap(sqlstr); System.out.println(map); } //{id=1, username= The east , age=21}
Two returned results will report an error . because map The key of is unique .

An error will also be reported if there is no returned result .

3. queryForList () Method
The query results are encapsulated as list aggregate , Each record will be encapsulated in map aggregate , In the package in list in .
@Test public void test3(){ String sqlstr="select * from t1"; List<Map<String, Object>> maps = template.queryForList(sqlstr); for (Map<String, Object> map : maps) { System.out.println(map); } }
4. query() Method
This method is most commonly used .
new BeanPropertyRowMapper< class >( class .class)
return
JavaBeanEncapsulated objects .First, create the corresponding class
package com.sql.jdbctemplate; public class Role { private Integer id; private String username; private Integer age;// Use the referenced data type to prevent null values in the database (null) Data of public Role(Integer id, String username, Integer age) { this.id = id; this.username = username; this.age = age; } public Role() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "Role{" + "id=" + id + ", username='" + username + '\'' + ", age=" + age + '}'; } }The first method ( More complicated , Not recommended ).

The second method
@Test public void test4(){ String sqlstr="select * from t1"; // Using generics and reflection will correspond to JavaBean Load into memory for use List<Role> list= template.query(sqlstr,new BeanPropertyRowMapper<Role>(Role.class)); for(Role r : list){ System.out.println(r); } }
** notes :** If fields and
beanFields in do not match , Can be inSQLAlias in statement .
5. queryForObject() Method
Generally used to execute Aggregate functions Of
sqlsentence , for examplecount,sum,avg@Test public void test5(){ String sqlstr="select count(1) from t1"; // except SQL Statement also passes in the type of the return value , The return value is received with the specified type Long count=template.queryForObject(sqlstr,Long.class); System.out.println(count); }
5. Supplement of shortcut keys
- Return value :idea in
ctrl+Alt+VQuickly generate return values . - for loop :
iterenhance for loop ,foriOrdinary for loop .
Continue to work hard , It's a big thing !
边栏推荐
- R language uses DALEX package to explain and analyze the machine learning model built by H2O package: summary and Practice
- MySql语句查询某一级节点的所有子节点
- 人脸识别神经网络实现
- 支付宝DTS架构
- A usage exploration of entitymanagerfactory and entitymanager
- 項目部署(簡版)
- The 12th Blue Bridge Cup embedded design and development project
- Heidelberg CP2000 circuit board maintenance printer host controller operation and maintenance precautions
- With only 5000 lines of code, AI renders 100 million landscape paintings on v853
- Concepts and differences of bit, bit, byte and word
猜你喜欢

好玩的代码雨,在线分享给大家~-

Activiti工作流使用之项目实例

Dynamic memory management

Huck hurco industrial computer maintenance winmax CNC machine tool controller maintenance

9. Ray tracing

pyqt5使用QPainter绘制坐标轴并显示散点图

“我最想要的六种编程语言!”

JDBC的学习以及简单封装

简述redis特点及其应用场景

SPR:SUPERVISED PERSONALIZED RANKING BASED ON PRIOR KNOWLEDGE FOR RECOMMENDATION
随机推荐
Gerrit 使用操作手册
EntityManagerFactory和EntityManager的一个用法探究
ShardingSphere分库分表方案
开发必备之Idea使用
Dynamic memory management
Déploiement du projet (version abrégée)
图片模糊处理批量生产模糊数据集
C1--Vivado配置VS Code文本编辑器环境2022-07-21
adb常用命令
使用pytorch实现基于VGG 19预训练模型的鲜花识别分类器,准确度达到97%
Pyqt5 use qpainter to draw the coordinate axis and display the scatter diagram
52832Dongle的安装
R language uses DALEX package to explain and analyze the machine learning model built by H2O package: summary and Practice
Cadence learning path (VIII) PCB placement components
What does resource pooling and resource pooling mean?
[visual slam] orb slam: tracking and mapping recognizable features
[swift bug] Xcode prompt error running playground: failed to prepare for communication with playground
Concepts et différences de bits, bits, octets et mots
cuda10.0配置pytorch1.7.0+monai0.9.0
单点登录-认证服务器与客户端的session过期时间如何统一
