当前位置:网站首页>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
边栏推荐
- Pytorch learning record (XI): data enhancement, torchvision Explanation of various functions of transforms
- Chapter 3 of linear algebra - Elementary Transformation of matrix and system of linear equations
- Pytorch notes - complete code for linear regression & manual or automatic calculation of gradient code comparison
- 你不能访问此共享文件夹,因为你组织的安全策略阻止未经身份验证的来宾访问
- SQL注入
- Fundamentals of digital image processing (Gonzalez) I
- 对比学习论文——[MoCo,CVPR2020]Momentum Contrast for Unsupervised Visual Representation Learning
- Pytorch学习记录(十三):循环神经网络((Recurrent Neural Network)
- CONDA virtual environment management (create, delete, clone, rename, export and import)
- Anaconda安装PyQt5 和 pyqt5-tools后没有出现designer.exe的问题解决
猜你喜欢
基于thymeleaf实现数据库图片展示到浏览器表格
Font shape `OMX/cmex/m/n‘ in size <10.53937> not available (Font) size <10.95> substituted.
Pytorch learning record (XI): data enhancement, torchvision Explanation of various functions of transforms
Pyqy5 learning (4): qabstractbutton + qradiobutton + qcheckbox
编程记录——图片旋转函数scipy.ndimage.rotate()的简单使用和效果观察
去噪论文阅读——[CVPR2022]Blind2Unblind: Self-Supervised Image Denoising with Visible Blind Spots
给yarn配置国内镜像加速器
CONDA virtual environment management (create, delete, clone, rename, export and import)
Linear algebra Chapter 2 - matrices and their operations
Denoising paper - [noise2void, cvpr19] noise2void learning denoising from single noise images
随机推荐
图像恢复论文简记——Uformer: A General U-Shaped Transformer for Image Restoration
filebrowser实现私有网盘
You cannot access this shared folder because your organization's security policy prevents unauthenticated guests from accessing it
Pytorch学习记录(十一):数据增强、torchvision.transforms各函数讲解
线性代数第二章-矩阵及其运算
Latex quick start
umi官网yarn create @umijs/umi-app 报错:文件名、目录名或卷标语法不正确
Remedy after postfix becomes a spam transit station
Unsupervised denoising - [tmi2022] ISCL: dependent self cooperative learning for unpaired image denoising
异常的处理:抓抛模型
无监督去噪——[TMI2022]ISCL: Interdependent Self-Cooperative Learning for Unpaired Image Denoising
PyQy5学习(三):QLineEdit+QTextEdit
开发环境 EAS登录 license 许可修改
Fundamentals of in-depth learning -- a simple understanding of meta learning (from Li Hongyi's course notes)
Fundamentals of SQL: first knowledge of database and SQL - installation and basic introduction - Alibaba cloud Tianchi
Pytorch學習記錄(十三):循環神經網絡((Recurrent Neural Network)
Pytorch learning record (7): skills in processing data and training models
How to use comparative learning to do unsupervised - [cvpr22] training & [eccv20] image translation
Pytorch notes - get familiar with the network construction method by building RESNET (complete code)
Pytorch learning record (XI): data enhancement, torchvision Explanation of various functions of transforms