当前位置:网站首页>Database connection pool & jdbctemplate
Database connection pool & jdbctemplate
2022-07-05 12:33:00 【It Chunhe】
Catalog
1.2.1、C3P0 Database connection pool
1.2.2、Druid Database connection pool
1、 Database connection pool
1.1、 brief introduction
1、 Database connection pool : In short , It's actually a container ( aggregate ), Container for storing database connection objects .
When the system is initialized , The container is created , Some connection objects will be requested in the container , When the user comes to access the database , Get the connection object from the container , After the user visits , The connection object is returned to the container .
2. The benefits of using connection pools :
1. Saving resource , Lifting performance
2. Efficient user access , Faster response3. Realization :
1. Standard interface :DataSource be located javax.sql It's a bag
1. Method :
Get the connection :getConnection()
Return connection :Connection.close().If the connection object Connection It's taken from the connection pool , So called Connection.close() Method , The connection will no longer be closed . But return the connection
4、 Common database connection pool :
1. C3P0: Database connection pool technology
2. Druid: Database connection pool implementation technology , Provided by Alibaba5、 Use of jar Package download address :jar Package download
1.2、 Use (quickstart)
1.2.1、C3P0 Database connection pool
Use steps :
1. Import jar package ( Two ) c3p0-0.9.5.2.jar mchange-commons-java-0.2.12.jar ,
Don't forget to import database drivers jar package jar Package download address
2. Define configuration file :
name : c3p0.properties perhaps c3p0-config.xml
route : Put the document directly in src Under the directory .3. Create core objects Database connection pool object ComboPooledDataSource
4. Get the connection : getConnection
1、 Import jar package
2、 To write c3p0.xml The configuration file
<c3p0-config>
<!-- Use the default configuration to read connection pool objects -->
<default-config>
<!-- Connection parameters -->
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/day10</property>
<property name="user">root</property>
<property name="password">123456</property>
<!-- Connection pool parameters -->
<property name="initialPoolSize">5</property>
<property name="maxPoolSize">10</property>
<property name="checkoutTimeout">3000</property>
</default-config>
<named-config name="otherc3p0">
<!-- Connection parameters -->
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/study</property>
<property name="user">root</property>
<property name="password">123456</property>
<!-- Connection pool parameters -->
<property name="initialPoolSize">5</property>
<property name="maxPoolSize">8</property>
<property name="checkoutTimeout">1000</property>
</named-config>
</c3p0-config>
3、 code
public class C3p0Test {
public static void main(String[] args) throws SQLException {
// TODO 1、 obtain datasource
ComboPooledDataSource dataSource = new ComboPooledDataSource();
// TODO 2、 obtain connection
Connection connection = dataSource.getConnection();
// TODO 3、 Definition sql
String sql = "select * from person";
// TODO 4、 perform sql
ResultSet resultSet = connection.createStatement().executeQuery(sql);
// TODO 5、 Print query data
while (resultSet.next()){
String name = resultSet.getString("name");
String email = resultSet.getString("email");
System.out.println(name + "=======" + email);
}
// TODO 6、 Release resources
resultSet.close();
connection.close();
}
}
1.2.2、Druid Database connection pool
Druid: Database connection pool implementation technology , Provided by Alibaba
1. step :
1. Import jar package druid-1.0.9.jar
2. Define configuration file :
yes properties Formal
You can call it anything , It can be placed in any directory
3. Load profile Properties
4. Get database connection pool object : From the factory DruidDataSourceFactory
5. Get the connection :getConnection
1、 Import jar package
2、 To write druid Configuration file for
druid.properties
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/day10
username=root
password=123456
initialSize=5
maxActive=10
maxWait=3000
3、 code
public class DruidTest {
public static void main(String[] args) throws Exception {
// TODO 1、 Load profile
Properties properties = new Properties();
InputStream is = DruidTest.class.getClassLoader().getResourceAsStream("druid.properties");
properties.load(is);
// TODO 2、 establish datasource
DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
// TODO 3、 Get database connection object
Connection connection = dataSource.getConnection();
// TODO 4、 Print objects directly See if you can get the database connection object
System.out.println(connection);
}
}
2、JDBCTemplate Use
Use JDBCTemplate It can greatly reduce our writing jdbc Code for To simplify our development
jdbctemplate A quick start to
1、 Import jar package
2、 code
public class JDBCTemplate_quickstart {
public static void main(String[] args) throws Exception {
// TODO 1、 Load profile
Properties properties = new Properties();
InputStream is = DruidTest.class.getClassLoader().getResourceAsStream("druid.properties");
properties.load(is);
// TODO 2、 establish datasource
DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
// TODO 3、 establish JDBCTemplate object Need to pass on a datasource
JdbcTemplate template = new JdbcTemplate(dataSource);
// TODO 4、 Definition sql
String sql = "update person set addr = ' panama ' where id = ?";
int count = template.update(sql,5); // take id by 5 Change your address to Panama
System.out.println(count); // Number of rows affected 1
// TODO Use jdbcTemplate It can greatly simplify the amount of our code Only care about sql
}
}
3、 test
But the above code is still a lot , Then the tool classes we extracted before are used
1、 Create a new one util package , Put the extracted tool classes into the toolkit
// This is a jdbc Tool class of
public class JdbcUtil {
// Define a member variable datasource
private static DataSource dataSource;
static {
try {
// 1、 establish properties Collection classes
Properties properties = new Properties();
// 2、 Load profile
InputStream resourceAsStream = JdbcUtil.class.getClassLoader().getResourceAsStream("druid.properties");
properties.load(resourceAsStream);
// 3、 Use database connection pool druid
dataSource = DruidDataSourceFactory.createDataSource(properties);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* return datasource Methods
* @return
*/
public static DataSource getDataSource(){
return dataSource;
}
/**
* Get database connection object
* @return Data connection objects
*/
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
/**
* Release resources
*
* @param stmt
* @param conn
*/
public static void close(Statement stmt, Connection conn) {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(PreparedStatement pstmt, Connection conn) {
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* Release resources
*
* @param stmt
* @param conn
*/
public static void close(ResultSet rs, Statement stmt, Connection conn) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(ResultSet rs, PreparedStatement stmt, Connection conn) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
2、 Use JDBCTemplate
public class JDBCTemplate_quickstart2 {
public static void main(String[] args) throws Exception {
// 1、 Create a template object
JdbcTemplate template = new JdbcTemplate(JdbcUtil.getDataSource());
// 2、 Definition sql
String sql = "select count(*) from person";
// 3、 Use template perform sql
Integer count = template.queryForObject(sql, Integer.class);
System.out.println(count);
}
}
This makes it look more concise And we just need to focus on sql Sentence can be used
边栏推荐
- MySQL storage engine
- Embedded software architecture design - message interaction
- Swift - add navigation bar
- UNIX socket advanced learning diary - advanced i/o functions
- MySQL view
- Two minutes will take you to quickly master the project structure, resources, dependencies and localization of flutter
- MySQL data table operation DDL & data type
- 一款新型的智能家居WiFi选择方案——SimpleWiFi在无线智能家居中的应用
- Storage Basics
- Learn the memory management of JVM 02 - memory allocation of JVM
猜你喜欢
MySQL storage engine
How to clear floating?
A guide to threaded and asynchronous UI development in the "quick start fluent Development Series tutorials"
Take you two minutes to quickly master the route and navigation of flutter
Migrate data from Mysql to neo4j database
Pytorch two-layer loop to realize the segmentation of large pictures
什么是数字化存在?数字化转型要先从数字化存在开始
Third party payment interface design
About cache exceptions: solutions for cache avalanche, breakdown, and penetration
UNIX socket advanced learning diary -ipv4-ipv6 interoperability
随机推荐
MySQL basic operation -dql
How can beginners learn flutter efficiently?
Introduction to GNN
Why learn harmonyos and how to get started quickly?
GPON technical standard analysis I
Select drop-down box realizes three-level linkage of provinces and cities in China
Matlab superpixels function (2D super pixel over segmentation of image)
Swift - enables textview to be highly adaptive
MySQL installation, Windows version
Image hyperspectral experiment: srcnn/fsrcnn
MySQL data table operation DDL & data type
Get data from the database when using JMeter for database assertion
Pytoch uses torchnet Classerrormeter in meter
Basic operations of MySQL data table, addition, deletion and modification & DML
POJ-2499 Binary Tree
MySQL view
Four operations and derivative operations of MATLAB polynomials
Learn the memory management of JVM 03 - Method area and meta space of JVM
Clear neo4j database data
ZABBIX agent2 monitors mongodb nodes, clusters and templates (official blog)