当前位置:网站首页>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入门小笔记——利用简单例子观察前向传播各个层输出的size
- Pytorch learning record (XII): learning rate attenuation + regularization
- JVM series (3) -- memory allocation and recycling strategy
- 图解numpy数组矩阵
- 治療TensorFlow後遺症——簡單例子記錄torch.utils.data.dataset.Dataset重寫時的圖片維度問題
- LDCT图像重建论文——Eformer: Edge Enhancement based Transformer for Medical Image Denoising
- 创建企业邮箱账户命令
- EditorConfig
- Denoising paper - [noise2void, cvpr19] noise2void learning denoising from single noise images
- redhat实现目录下特定文本类型内关键字查找及vim模式下关键字查找
猜你喜欢

Anaconda

线性代数第二章-矩阵及其运算

Pytorch learning record (V): back propagation + gradient based optimizer (SGD, adagrad, rmsporp, Adam)

图像恢复论文简记——Uformer: A General U-Shaped Transformer for Image Restoration

Pyemd installation and simple use

Software architecture design - software architecture style

Pyqy5 learning (4): qabstractbutton + qradiobutton + qcheckbox

Font shape `OMX/cmex/m/n‘ in size <10.53937> not available (Font) size <10.95> substituted.

创建二叉树

Anaconda
随机推荐
Paper on Image Restoration - [red net, nips16] image restoration using very deep revolutionary encoder decoder networks wi
治疗TensorFlow后遗症——简单例子记录torch.utils.data.dataset.Dataset重写时的图片维度问题
A general U-shaped transformer for image restoration
Pyqy5 learning (4): qabstractbutton + qradiobutton + qcheckbox
On traversal of binary tree
The attendance client date of K / 3 wise system can only be selected to 2019
Illustrate the significance of hashcode
Pyqy5 learning (III): qlineedit + qtextedit
PyTorch笔记——观察DataLoader&用torch构建LeNet处理CIFAR-10完整代码
线代第四章-向量组的线性相关
Pytorch learning record (XI): data enhancement, torchvision Explanation of various functions of transforms
How to use comparative learning to do unsupervised - [cvpr22] training & [eccv20] image translation
ValueError: loaded state dict contains a parameter group that doesn‘t match the size of optimizer‘s
Pyqy5 learning (2): qmainwindow + QWidget + qlabel
自动控制(韩敏版)
图解HashCode存在的意义
Traitement des séquelles du flux de Tensor - exemple simple d'enregistrement de torche. Utils. Données. Dataset. Problème de dimension de l'image lors de la réécriture de l'ensemble de données
umi官网yarn create @umijs/umi-app 报错:文件名、目录名或卷标语法不正确
Pytorch學習記錄(十三):循環神經網絡((Recurrent Neural Network)
Software architecture design - software architecture style