当前位置:网站首页>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=30003、 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

边栏推荐
- Anaconda creates a virtual environment and installs pytorch
- GPON other manufacturers' configuration process analysis
- ZABBIX agent2 monitors mongodb templates and configuration operations
- Principle of universal gbase high availability synchronization tool in Nanjing University
- Redis highly available sentinel cluster
- II. Data type
- Understanding the architecture type of mobile CPU
- Detailed steps for upgrading window mysql5.5 to 5.7.36
- MySQL index (1)
- Pytoch counts the number of the same elements in the tensor
猜你喜欢

The relationship between the size change of characteristic graph and various parameters before and after DL convolution operation

Intern position selection and simplified career development planning in Internet companies

Pytorch two-layer loop to realize the segmentation of large pictures

Pytoch uses torchnet Classerrormeter in meter

Implementing Yang Hui triangle with cyclic queue C language
Two minutes will take you to quickly master the project structure, resources, dependencies and localization of flutter
[email protected] (using password"/>Solve the error 1045 of Navicat creating local connection -access denied for user [email protected] (using password

Redis highly available sentinel cluster

Four operations and derivative operations of MATLAB polynomials

Migrate data from Mysql to neo4j database
随机推荐
Master the new features of fluent 2.10
Implementing Yang Hui triangle with cyclic queue C language
Correct opening method of redis distributed lock
Keras implements verification code identification
Understand kotlin from the perspective of an architect
Flutter2 heavy release supports web and desktop applications
Introduction to GNN
Simple production of wechat applet cloud development authorization login
Read and understand the rendering mechanism and principle of flutter's three trees
One article tells the latest and complete learning materials of flutter
mysql拆分字符串做条件查询
Hexadecimal conversion summary
How can beginners learn flutter efficiently?
Swift - add navigation bar
How to design an interface?
[HDU 2096] 小明A+B
Redis's memory elimination mechanism, read this article is enough.
The evolution of mobile cross platform technology
Intern position selection and simplified career development planning in Internet companies
ZABBIX customized monitoring disk IO performance