Salmon的全栈知识 Salmon的全栈知识
首页
  • JavaSE
  • JavaWeb
  • Spring生态
  • JUC
  • JVM
  • Netty
  • Java各版本特性
  • 23种设计模式
  • Maven
  • Java常用框架
  • Dubbo
  • OpenFeign
  • Nacos
  • Zookeeper
  • Sentinel
  • Seata
  • SpringCloud Gateway
  • Apollo
  • Eureka
  • Go基础
  • Gin
  • SQL数据库

    • MySQL
    • Oracle
  • NoSQL数据库

    • Redis
    • MongoDB
    • ElasticSearch
  • 消息中间件

    • RabbitMQ
    • RocketMQ
    • Kafka
    • ActiveMQ
    • MQTT
    • NATS
  • 网关中间件

    • Nginx
  • Linux
  • Docker
  • Git
  • K8s
  • Solidity
  • Java
  • 计算机网络
  • 操作系统
GitHub (opens new window)
首页
  • JavaSE
  • JavaWeb
  • Spring生态
  • JUC
  • JVM
  • Netty
  • Java各版本特性
  • 23种设计模式
  • Maven
  • Java常用框架
  • Dubbo
  • OpenFeign
  • Nacos
  • Zookeeper
  • Sentinel
  • Seata
  • SpringCloud Gateway
  • Apollo
  • Eureka
  • Go基础
  • Gin
  • SQL数据库

    • MySQL
    • Oracle
  • NoSQL数据库

    • Redis
    • MongoDB
    • ElasticSearch
  • 消息中间件

    • RabbitMQ
    • RocketMQ
    • Kafka
    • ActiveMQ
    • MQTT
    • NATS
  • 网关中间件

    • Nginx
  • Linux
  • Docker
  • Git
  • K8s
  • Solidity
  • Java
  • 计算机网络
  • 操作系统
GitHub (opens new window)
npm

(进入注册为作者充电)

  • JUnit单元测试
  • JDBC
  • JDBC连接池&JDBCTemplate
    • 1. 数据库连接池
      • 1.1 概念
      • 1.2 好处
      • 1.3 实现方式
      • 标准接口
      • javax.sql.DataSource
      • 常见实现:
      • 1.4 C3P0 使用步骤
      • 1.5 Druid 使用步骤
      • 1.6 JDBC 工具类封装
      • JDBCUtils
    • 2. Spring JDBC
      • 2.1 概述
      • 2.2 使用步骤
      • 2.3 示例练习代码
      • 2.4 JavaBean:Emp 示例结构(简化)
  • XML
  • Tomcat&Servlet
  • Servlet&HTTP&Request
  • Response
  • Cookie&Session
  • EL&JSTL
  • Filter&Listener
  • 《JavaWeb》笔记
Salmon
2025-07-21
目录

JDBC连接池&JDBCTemplate

# 1. 数据库连接池

# 1.1 概念

数据库连接池:本质是一个容器,用来存放数据库连接对象。

  • 系统初始化时创建连接池并生成一些连接对象。
  • 用户访问数据库时从连接池中获取连接,用完后归还而不是关闭连接。

# 1.2 好处

  • 节约资源(复用连接)
  • 提高性能(无需频繁创建连接)

# 1.3 实现方式

# 标准接口

# javax.sql.DataSource

  • 获取连接:getConnection()
  • 归还连接:Connection.close() —— 实际是归还而不是关闭

# 常见实现:

  • C3P0:老牌连接池
  • Druid:阿里巴巴开源,功能更强、性能更高

# 1.4 C3P0 使用步骤

  1. 导入 jar 包:

    • c3p0-0.9.5.2.jar
    • mchange-commons-java-0.2.12.jar
    • 数据库驱动(如 MySQL JDBC)
  2. 配置文件(放在 src 目录):

    • c3p0.properties 或 c3p0-config.xml
  3. 核心代码:

DataSource ds = new ComboPooledDataSource();
Connection conn = ds.getConnection();

# 1.5 Druid 使用步骤

  1. 导入 jar 包:druid-1.0.9.jar
  2. 配置文件:
    • .properties 格式,位置和文件名都可自定义
  3. 核心代码:
Properties pro = new Properties();
InputStream is = DruidDemo.class.getClassLoader().getResourceAsStream("druid.properties");
pro.load(is);

DataSource ds = DruidDataSourceFactory.createDataSource(pro);
Connection conn = ds.getConnection();

# 1.6 JDBC 工具类封装

# JDBCUtils

public class JDBCUtils {

    private static DataSource ds;

    static {
        try {
            Properties pro = new Properties();
            pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
            ds = DruidDataSourceFactory.createDataSource(pro);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }

    public static void close(ResultSet rs, Statement stmt, Connection conn) {
        try { if (rs != null) rs.close(); } catch (Exception e) { e.printStackTrace(); }
        try { if (stmt != null) stmt.close(); } catch (Exception e) { e.printStackTrace(); }
        try { if (conn != null) conn.close(); } catch (Exception e) { e.printStackTrace(); }
    }

    public static DataSource getDataSource() {
        return ds;
    }
}

# 2. Spring JDBC

# 2.1 概述

  • Spring 对 JDBC 的封装。
  • 主要使用 JdbcTemplate 类。

# 2.2 使用步骤

  1. 导入依赖 jar 包
  2. 创建 JdbcTemplate 对象(依赖数据源 DataSource)
JdbcTemplate template = new JdbcTemplate(ds);
  1. 常用方法
方法 说明
update() 执行 DML 操作(增、删、改)
queryForMap() 查询一条记录,封装为 Map
queryForList() 查询多条记录,封装为 List<Map>
query() 查询记录,封装为 JavaBean
queryForObject() 一般用于聚合查询,如 count(*)

# 2.3 示例练习代码

import cn.itcast.domain.Emp;
import cn.itcast.utils.JDBCUtils;
import org.junit.Test;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

public class JdbcTemplateDemo2 {

    // Junit 单元测试,可以让方法独立执行

    // 1. 获取 JdbcTemplate 对象
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

    /**
     * 1. 修改 1 号数据的 salary 为 10000
     */
    @Test
    public void test1() {
        // 2. 定义 SQL
        String sql = "update emp set salary = 10000 where id = 1001";
        // 3. 执行 SQL
        int count = template.update(sql);
        System.out.println(count);
    }

    /**
     * 2. 添加一条记录
     */
    @Test
    public void test2() {
        String sql = "insert into emp(id, ename, dept_id) values (?, ?, ?)";
        int count = template.update(sql, 1015, "郭靖", 10);
        System.out.println(count);
    }

    /**
     * 3. 删除刚才添加的记录
     */
    @Test
    public void test3() {
        String sql = "delete from emp where id = ?";
        int count = template.update(sql, 1015);
        System.out.println(count);
    }

    /**
     * 4. 查询 id 为 1001 的记录,将其封装为 Map 集合
     * 注意:这个方法查询的结果集长度只能是 1
     */
    @Test
    public void test4() {
        String sql = "select * from emp where id = ? or id = ?";
        Map<String, Object> map = template.queryForMap(sql, 1001, 1002);
        System.out.println(map);
        // {id=1001, ename=孙悟空, job_id=4, mgr=1004, joindate=2000-12-17, salary=10000.00, bonus=null, dept_id=20}
    }

    /**
     * 5. 查询所有记录,将其封装为 List
     */
    @Test
    public void test5() {
        String sql = "select * from emp";
        List<Map<String, Object>> list = template.queryForList(sql);

        for (Map<String, Object> stringObjectMap : list) {
            System.out.println(stringObjectMap);
        }
    }

    /**
     * 6. 查询所有记录,将其封装为 Emp 对象的 List 集合(手动映射方式)
     */
    @Test
    public void test6() {
        String sql = "select * from emp";
        List<Emp> list = template.query(sql, new RowMapper<Emp>() {
            @Override
            public Emp mapRow(ResultSet rs, int i) throws SQLException {
                Emp emp = new Emp();

                int id = rs.getInt("id");
                String ename = rs.getString("ename");
                int job_id = rs.getInt("job_id");
                int mgr = rs.getInt("mgr");
                Date joindate = rs.getDate("joindate");
                double salary = rs.getDouble("salary");
                double bonus = rs.getDouble("bonus");
                int dept_id = rs.getInt("dept_id");

                emp.setId(id);
                emp.setEname(ename);
                emp.setJob_id(job_id);
                emp.setMgr(mgr);
                emp.setJoindate(joindate);
                emp.setSalary(salary);
                emp.setBonus(bonus);
                emp.setDept_id(dept_id);

                return emp;
            }
        });

        for (Emp emp : list) {
            System.out.println(emp);
        }
    }

    /**
     * 6-2. 查询所有记录,将其封装为 Emp 对象的 List 集合(自动映射方式)
     */
    @Test
    public void test6_2() {
        String sql = "select * from emp";
        List<Emp> list = template.query(sql, new BeanPropertyRowMapper<Emp>(Emp.class));
        for (Emp emp : list) {
            System.out.println(emp);
        }
    }

    /**
     * 7. 查询总记录数
     */
    @Test
    public void test7() {
        String sql = "select count(id) from emp";
        Long total = template.queryForObject(sql, Long.class);
        System.out.println(total);
    }
}

# 2.4 JavaBean:Emp 示例结构(简化)

public class Emp {
    private Integer id;
    private String ename;
    private Integer job_id;
    private Integer mgr;
    private Date joindate;
    private Double salary;
    private Double bonus;
    private Integer dept_id;
    
    // 省略 getter/setter 和 toString()
}
上次更新: 2025/07/23, 01:37:33
JDBC
XML

← JDBC XML→

Theme by Vdoing | Copyright © 2022-2025 Salmon's Blog
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式