当前位置:网站首页>JDBC--Druid数据库连接池以及Template基本用法
JDBC--Druid数据库连接池以及Template基本用法
2022-08-02 02:56:00 【兄dei!】
数据库连接池
1. 概念:其实就是一个容器(集合),存放数据库连接的容器。
当系统初始化好后,容器被创建,容器中会申请一些连接对象,当用户来访问数据库时,从容器中获取连接对象,用户访问完之后,会将连接对象归还给容器。
2. 好处:
1. 节约资源
2. 用户访问高效
Druid:数据库连接池实现技术,由阿里巴巴提供
使用步骤:
1. 导入jar包 druid-1.0.9.jar
2. 定义配置文件:
* 是properties形式的
* 可以叫任意名称,可以放在任意目录下
3. 加载配置文件。Properties
4. 获取数据库连接池对象:通过工厂来来获取 DruidDataSourceFactory
5. 获取连接:getConnection
配置文件:
driverClassName=com.mysql.jdbc.Driver //驱动加载
url=jdbc:mysql://127.0.0.1:3306/DB1 //注册驱动
username=root //连接数据库的用户名
password=root //连接数据库的密码
initialSize=5 //初始化时池中建立的物理连接个数
maxActive=10 //最大的可活跃的连接池数量
maxWait=3000 //获取连接时最大等待时间,单位毫秒,超过连接就会失效。
使用了druid连接池的工具类
public class JDBCUtils {
private static DataSource ds;
static {
try {
//加载配置文件
Properties pro=new Properties();
InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("Druid.properties");
pro.load(is);
//通过工厂获取连接池对象
ds = DruidDataSourceFactory.createDataSource(pro);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
//获取连接
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
//获取数据库连接对象
public static DataSource getDataSource(){
return ds;
}
//重载close方法
public static void close(Statement stmt,Connection conn){
close(null,stmt,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();
}
}
}
}
使用Druid得到连接Connection就可以执行相关JDBC操作了。
当然还有更方便的方法——JdbcTemplate
Spring JDBC
* Spring框架对JDBC的简单封装。提供了一个JDBCTemplate对象简化JDBC的开发
* 步骤:
1. 导入jar包
2. 创建JdbcTemplate对象。依赖于数据源DataSource
* JdbcTemplate template = new JdbcTemplate(ds);
3. 调用JdbcTemplate的方法来完成CRUD的操作
* update():执行DML语句。增、删、改语句
* queryForMap():查询结果将结果集封装为map集合,将列名作为key,将值作为value 将这条记录封装为一个map集合
* 注意:这个方法查询的结果集长度只能是1
* queryForList():查询结果将结果集封装为list集合
* 注意:将每一条记录封装为一个Map集合,再将Map集合装载到List集合中
* query():查询结果,将结果封装为JavaBean对象
* query的参数:RowMapper
* 一般我们使用BeanPropertyRowMapper实现类。可以完成数据到JavaBean的自动封装
* new BeanPropertyRowMapper<类型>(类型.class)
* queryForObject:查询结果,将结果封装为对象
* 一般用于聚合函数的查询
增删改:用update
public class tempDemo {
private JdbcTemplate template=new JdbcTemplate(JDBCUtils2.getDataSource());
public void test(){
//使用template完成增删改
String add_sql="insert into user values(NULL,'马化腾','123')";
String de_sql="delete from user where id = 5 ";
String up_sql="UPDATE USER SET username='马云' WHERE id =1";
//update():执行DML语句。增、删、改语句
template.update(add_sql);
template.update(de_sql);
template.update(up_sql);
}
public static void main(String[] args) {
new tempDemo().test();//调用测试方法
}
}
-->>>
查询:用query系列
public class tempDemo {
private JdbcTemplate template=new JdbcTemplate(JDBCUtils2.getDataSource());
public void test(){
//使用template完成增删改
String add_sql="insert into user values(NULL,'马化腾','123')";
String de_sql="delete from user where id = 5 ";
String up_sql="UPDATE USER SET username='马云' WHERE id =1";
//update():执行DML语句。增、删、改语句
template.update(add_sql);
template.update(de_sql);
template.update(up_sql);
}
public void test2(){
//使用template完成查询操作
//定义sql
String sql="select * from user where id = ?";
String sql2="select id from user";
String sql3="select * from user";
//执行并打包成一个user类
User user = template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), 1);//最后的参数传的是?的值
//执行打包成list集合
List<Integer> list = template.queryForList(sql2, Integer.class);
//执行并把user打包成集合
List<User> query = template.query(sql3, new BeanPropertyRowMapper<User>(User.class));
System.out.println("执行并打包成一个user类"+user);
System.out.println("执行打包成list集合"+list);
System.out.println("执行并把user打包成集合"+query);
}
public static void main(String[] args) {
// new tempDemo().test();//调用测试方法
new tempDemo().test2();
}
}
输出结果:
信息: {dataSource-1} inited
执行并打包成一个user类User{id=1, username='马云', password='123'}
执行打包成list集合[1, 2, 7]
执行并把user打包成集合[User{id=1, username='马云', password='123'}, User{id=2, username='lisi', password='123'}, User{id=7, username='马化腾', password='123'}]
边栏推荐
- 消息队列经典十连问
- CentOS7安装Oracle数据库的全流程
- mysql8.0.28 download and installation detailed tutorial, suitable for win11
- Hit the programmer interview scene: What did Baidu interviewers ask me?
- WebShell connection tools (Chinese kitchen knife, WeBaCoo, Weevely) use
- MySQL八股文背诵版
- 【LeetCode】104.二叉树的最大深度
- ASP WebShell 后门脚本与免杀
- 合奥科技网络 面试(含参考答案)
- AcWing 1053. 修复DNA 题解(状态机DP、AC自动机)
猜你喜欢
MySQL8 -- use msi (graphical user interface) under Windows installation method
MySQL index optimization in practice
2022牛客多校四_G M
合奥科技网络 面试(含参考答案)
ReentrantLock工作原理
WebShell Feature Value Summary and Detection Tool
很有意思的经历,很有意思的项目--文件夹对比工具
消息队列经典十连问
【每日一道LeetCode】——1. 两数之和
[Daily LeetCode]——1. The sum of two numbers
随机推荐
【LeetCode】145. Postorder Traversal of Binary Tree
第10章_索引优化与查询优化
合奥科技网络 面试(含参考答案)
Qt自定义控件和模板分享
WebShell连接工具(中国菜刀、WeBaCoo、Weevely)使用
2W字!详解20道Redis经典面试题!(珍藏版)
IPFS部署及文件上传(golang)
* Compare version numbers
【LeetCode】144.二叉树的前序遍历
node:internal/modules/cjs/loader:936 throw err; ^ Error: Cannot find module ‘./scope‘
微服务:微智能在软件系统的简述
第二章——堆栈、队列
Go语学习笔记 - gorm使用 - gorm处理错误 Web框架Gin(十)
详解最强分布式锁工具:Redisson
【LeetCode】94.二叉树的中序遍历
analog IC layout-Parasitic effects
leetcode 143. 重排链表
【CNN记录】tensorflow slice和strided_slice
忽晴忽雨
Go语学习笔记 - gorm使用 - 表增删改查 Web框架Gin(八)