当前位置:网站首页>DBCP usage
DBCP usage
2022-04-23 06:00:00 【hanyc..】
The configuration file :
# connections setting up
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=true
username=root
password=123456
# Initialize connection
initialSize=10
# Maximum number of connections
maxActive=50
# Maximum free connection
maxIdle=20
# Minimum free connection
minIdle=5
# Timeout wait time in milliseconds 6000 millisecond /1000 be equal to 60 second
maxWait=60000
#JDBC The format of the connection attribute attribute attached to the driver when establishing the connection must be as follows :【 Property name =property;】
# Be careful :user And password Two attributes are explicitly passed , So there's no need to include them .
connectionProperties=useUnicode=true;characterEncoding=UTF8
# Specifies the automatic commit of connections created by the connection pool (auto-commit) state .
defaultAutoCommit=true
#driver default Specifies the read-only... Of the connection created by the connection pool (read-only) state .
# If the value is not set , be “setReadOnly” Method will not be called .( Some drivers do not support read-only mode , Such as :Informix)
defaultReadOnly=
#driver default Specify the transaction level of the connection created by the connection pool (TransactionIsolation).
# The available values are one of the following :( Details visible javadoc.)NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE
defaultTransactionIsolation=READ_COMMITTED
Tool class extraction :
package com.hyc.study05.utils;
import com.hyc.study02.utils.JDBCUtils;
import org.apache.commons.dbcp.BasicDataSourceFactory;
import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class DBCPUtils {
public static DataSource dataSource = null;
static {
try {
InputStream inputStream = JDBCUtils.class.getClassLoader().getResourceAsStream("dbcp.properties");
Properties properties = new Properties();
properties.load(inputStream);
// create data source Factory mode --> establish
dataSource = BasicDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
// Get the connection
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();// Get the connection from the data source
}
// Release the connection
public static void release(Connection connection, Statement statement, ResultSet resultSet) {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
It is mainly in obtaining database connection and simple use JDBC A little difference between , After using the database connection pool , You don't need to write code to connect to the database .( Connection pool mainly implements DataSource Interface )
test :
package com.hyc.study05;
import com.hyc.study05.utils.DBCPUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
public class TestDBCP {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
//3、 Get database connection
connection = DBCPUtils.getConnection();
// Use ? Placeholders replace parameters
String sql = "INSERT INTO `users`(`id`,`NAME`,`PASSWORD`,`email`,`birthday`) " +
"VALUES (?,?,?,?,?);";
//4、 Access to perform sql The object of
// precompile sql, First write sql, Then don't execute
preparedStatement = connection.prepareStatement(sql);
// Assign parameters manually
preparedStatement.setInt(1, 4);
preparedStatement.setString(2, "hyc");
preparedStatement.setString(3, "123456");
preparedStatement.setString(4, "[email protected]");
//java.sql.Date It's database Date , Only the date information is included , It is java.util.Date( Contains the information of month, day, hour, minute and second ) Subclasses of
preparedStatement.setDate(5, new java.sql.Date(new Date().getTime()));
//5、 perform sql sentence
//6、 Return execution result set
int num = preparedStatement.executeUpdate();
if (num > 0) {
System.out.println(" Insert data succeeded !");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
//7、 Release the connection
DBCPUtils.release(connection, preparedStatement, resultSet);
}
}
}
版权声明
本文为[hanyc..]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230541159473.html
边栏推荐
- Write your own redistemplate
- Opensips (1) -- detailed process of installing opensips
- Pytorch learning record (V): back propagation + gradient based optimizer (SGD, adagrad, rmsporp, Adam)
- Filebrowser realizes private network disk
- Rsync for file server backup
- Reading of denoising papers - [cvpr2022] blind2blind: self supervised image denoising with visible blind spots
- What is the difference between the basic feasible solution and the basic feasible solution in linear programming?
- Pytorch Learning record (XIII): Recurrent Neural Network
- The attendance client date of K / 3 wise system can only be selected to 2019
- In depth source code analysis servlet first program
猜你喜欢
Unsupervised denoising - [tmi2022] ISCL: dependent self cooperative learning for unpaired image denoising
Font shape `OMX/cmex/m/n‘ in size <10.53937> not available (Font) size <10.95> substituted.
Pytorch——数据加载和处理
Pytorch学习记录(三):神经网络的结构+使用Sequential、Module定义模型
Pytorch learning record (V): back propagation + gradient based optimizer (SGD, adagrad, rmsporp, Adam)
开发环境 EAS登录 license 许可修改
Practical operation - Nacos installation and configuration
Pytorch学习记录(五):反向传播+基于梯度的优化器(SGD,Adagrad,RMSporp,Adam)
容器
Gaussian processes of sklearn
随机推荐
Pytorch learning record (III): structure of neural network + using sequential and module to define the model
Pytoch -- data loading and processing
PyQy5学习(三):QLineEdit+QTextEdit
Fundamentals of SQL: first knowledge of database and SQL - installation and basic introduction - Alibaba cloud Tianchi
Software architecture design - software architecture style
Use Matplotlib. In Jupiter notebook Pyplot server hangs up and crashes
Practical operation - Nacos installation and configuration
SQL基础:初识数据库与SQL-安装与基本介绍等—阿里云天池
Fundamentals of digital image processing (Gonzalez) II: gray transformation and spatial filtering
Linear algebra Chapter 2 - matrices and their operations
Fundamentals of digital image processing (Gonzalez) I
JDBC连接数据库
ValueError: loaded state dict contains a parameter group that doesn‘t match the size of optimizer‘s
图像恢复论文——[RED-Net, NIPS16]Image Restoration Using Very Deep Convolutional Encoder-Decoder Networks wi
String notes
Common programming records - parser = argparse ArgumentParser()
Pytorch learning record (IV): parameter initialization
线性规划问题中可行解,基本解和基本可行解有什么区别?
EditorConfig
Pytorch notes - get familiar with the network construction method by building RESNET (complete code)