当前位置:网站首页>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
边栏推荐
- Distributed cache architecture - cache avalanche & penetration & hit rate
- Implementing Yang Hui triangle with cyclic queue C language
- MySQL regular expression
- 嵌入式软件架构设计-消息交互
- Just a coincidence? The mysterious technology of apple ios16 is actually the same as that of Chinese enterprises five years ago!
- 7月华清学习-1
- Intern position selection and simplified career development planning in Internet companies
- Matlab boundarymask function (find the boundary of the divided area)
- MySQL splits strings for conditional queries
- Introduction to relational model theory
猜你喜欢
mysql拆分字符串做条件查询
A guide to threaded and asynchronous UI development in the "quick start fluent Development Series tutorials"
Redis highly available sentinel mechanism
Get all stock data of big a
Understand redis persistence mechanism in one article
Principle of universal gbase high availability synchronization tool in Nanjing University
MySQL transaction
C language structure is initialized as a function parameter
Third party payment interface design
Embedded software architecture design - message interaction
随机推荐
Xi IO flow
Master-slave mode of redis cluster
Introduction to relational model theory
Master the new features of fluent 2.10
C alarm design
The relationship between the size change of characteristic graph and various parameters before and after DL convolution operation
Understand redis persistence mechanism in one article
Get the variable address of structure member in C language
POJ-2499 Binary Tree
Storage Basics
Four operations and derivative operations of MATLAB polynomials
Handwriting blocking queue: condition + lock
Leetcode-1. Sum of two numbers (Application of hash table)
Recyclerview paging slide
Understanding the architecture type of mobile CPU
MySQL index - extended data
Select drop-down box realizes three-level linkage of provinces and cities in China
Seven polymorphisms
C language structure is initialized as a function parameter
Learn JVM garbage collection 02 - a brief introduction to the reference and recycling method area