当前位置:网站首页>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
边栏推荐
- Understand kotlin from the perspective of an architect
- Master-slave mode of redis cluster
- Simple production of wechat applet cloud development authorization login
- MySQL index (1)
- ZABBIX ODBC database monitoring
- Storage Basics
- The relationship between the size change of characteristic graph and various parameters before and after DL convolution operation
- POJ-2499 Binary Tree
- Redis clean cache
- Pytorch two-layer loop to realize the segmentation of large pictures
猜你喜欢
Pytoch implements tf Functions of the gather() function
Storage Basics
Redis highly available sentinel mechanism
Detailed steps for upgrading window mysql5.5 to 5.7.36
Read and understand the rendering mechanism and principle of flutter's three trees
NPM install reports an error
Get the variable address of structure member in C language
Pytoch monolayer bidirectional_ LSTM implements MNIST and fashionmnist data classification
What is digital existence? Digital transformation starts with digital existence
About cache exceptions: solutions for cache avalanche, breakdown, and penetration
随机推荐
Implementing Yang Hui triangle with cyclic queue C language
C language structure is initialized as a function parameter
Seven ways to achieve vertical centering
Redis highly available sentinel cluster
Correct opening method of redis distributed lock
ZABBIX 5.0 - LNMP environment compilation and installation
一款新型的智能家居WiFi选择方案——SimpleWiFi在无线智能家居中的应用
ZABBIX monitors mongodb (template and deployment operations)
Differences between IPv6 and IPv4 three departments including the office of network information technology promote IPv6 scale deployment
Two minutes will take you to quickly master the project structure, resources, dependencies and localization of flutter
struct MySQL
Select drop-down box realizes three-level linkage of provinces and cities in China
Understand kotlin from the perspective of an architect
MySQL function
Xi IO flow
PXE启动配置及原理
MySQL transaction
Learn the memory management of JVM 03 - Method area and meta space of JVM
[hdu 2096] Xiaoming a+b
【ijkplayer】when i compile file “compile-ffmpeg.sh“ ,it show error “No such file or directory“.