javaWeb基础之常用连接池

课程笔记Day30

  •  连接池
    
  •  Spring工具类
    

第一章 连接池

第01节 基础理论
1、什么是连接池

池的概念

概念描述:
	提前创建好的一堆对象,保存到内存当中,需要使用的时候,拿出来,用完之后,就归还回去。(可借可还)
	
举例说明,生活实例:
	定浩他是餐馆的老板,洪湖定浩小蒸龙虾。
	情况一:
		1. 有顾客上门就餐,定浩要亲自服务
		2. 为什么需要亲自服务啊?
			因为没有服务员,只有老板一人
	情况二:
		1. 定浩现在先需要招聘一个兼职(郭龙兼职服务员)
		2. 有顾客上门就餐,金铎去吃小龙虾,郭龙去服务金铎。
		3. 金铎就餐完毕,走人了。
		4. 定浩做了一件事情,解雇了郭龙。以为金铎已经不再就餐了。
		5. 有顾客上门就餐,黄杰去吃小龙虾
		6. 定浩发现没人啦? 又要去招人服务,招聘一个兼职(王汉兼职服务员)
		7. 黄杰顾客就餐完毕,走人了。
		8. 定浩做了一件事情,解雇了王汉。以为黄杰已经不再就餐了。
	情况三:
		1. 定浩现在发现问题,每次这么操作都很麻烦,有顾客就要招聘兼职,顾客走了,兼职要辞退。
		2. 现在定浩,就去招聘稳定的长期的服务员。(陈铭豪、陈龙、陈宇波)长期稳定的,要发工资,社保,公积金,福利
		3. 顾客上门就餐。一次性来了很多人。例如: 张改、张倩、张佑威、尚涵、张琦
		4. 定浩还会去招聘兼职(金铎、杨耿)
		5. 当顾客就餐完毕之后,会辞退兼职人员,本地员工 (陈铭豪、陈龙、陈宇波) 不会辞退。
2、常见的连接池

需要介绍的连接池

(1) C3P0  连接池  说明: 早期的项目,采用hibernate 会使用到 C3P0连接池。
(2) Druid 连接池  说明:这个连接池是 阿里巴巴的连接池,他的支付宝、淘宝都是采用的是 Druid 连接池

连接池原理说明

在这里插入图片描述

第02节 C3P0连接池
1、操作步骤
1. 准备数据库、准备数据表
2. 导入jar包
	mysql-connector-java-5.1.37-bin.jar
	mchange-commons-java-0.2.12.jar
	c3p0-0.9.5.2.jar
3. 导入配置文件 (要求:xml文件名称不能改变、xml文件必须放在 src文件夹下面)
	c3p0-config.xml
4. 编写Java代码
	A. 获取到连接池对象
	B. 获取到连接
	C. 当数据库操作完毕, 归还连接
2、准备工作

MySQL 数据库的代码准备

-- 1. 准备数据库
DROP DATABASE IF EXISTS mydb10;
CREATE DATABASE IF NOT EXISTS mydb10;
USE mydb10;

-- 2. 准备数据表
DROP TABLE IF EXISTS student;
CREATE TABLE IF NOT EXISTS student (
	id INT PRIMARY KEY AUTO_INCREMENT,
	sname VARCHAR(20),
	sage  INT
);

-- 3. 查询表信息
SELECT * FROM student;

配置文件 src/c3p0-config.properties

<c3p0-config>
  <!-- 使用默认的配置读取连接池对象 -->
  <default-config>
  	<!--  连接参数 -->
    <property name="driverClass">com.mysql.jdbc.Driver</property>
    <property name="jdbcUrl">jdbc:mysql://localhost:3306/mydb10</property>
    <property name="user">root</property>
    <property name="password">root</property>
    
    <!-- 连接池参数 -->
    <property name="initialPoolSize">5</property>
    <property name="maxPoolSize">10</property>
    <property name="checkoutTimeout">3000</property>
  </default-config>

  <named-config name="otherc3p0"> 
    <!--  连接参数 -->
    <property name="driverClass">com.mysql.jdbc.Driver</property>
    <property name="jdbcUrl">jdbc:mysql://localhost:3306/mydb10</property>
    <property name="user">root</property>
    <property name="password">root</property>
    
    <!-- 连接池参数 -->
    <property name="initialPoolSize">5</property>
    <property name="maxPoolSize">8</property>
    <property name="checkoutTimeout">1000</property>
  </named-config>
</c3p0-config>
3、写Java代码
//目标:C3P0连接池的快速入门
@SuppressWarnings("all")
public class Test01 {

    public static void main(String[] args) throws Exception {

        //1. 获取到连接池对象, 导入的包是 javax.sql.DataSource
        DataSource ds = new ComboPooledDataSource();

        //2. 获取到连接
        Connection conn = ds.getConnection();

        //3. 执行操作
        String sql = "INSERT INTO student VALUES (NULL,'定浩吧',18)";
        Statement stat = conn.createStatement();
        int lineNumber = stat.executeUpdate(sql);

        System.out.println("lineNumber = " + lineNumber);
        System.out.println(lineNumber > 0 ? "成功" : "失败");

        //4. 释放资源
        stat.close();
        conn.close();
    }
}
第03节 Druid连接池
1、操作步骤
1. 准备数据库、准备数据表
2. 导入jar包
	mysql-connector-java-5.1.37-bin.jar
	druid-1.0.9.jar
3. 导入配置文件 (位置任意,建议放在 src 文件夹下面,名称也是任意的)
	druid.properties
4. 编写Java代码
	A. 获取到配置文件的 properties 的对象
	B. 通过工厂去加载 DataSource 工厂的名称是 DruidDataSorceFactory
	C. 获取到连接 Connection的对象
	D. 获取到操作对象,执行SQL操作 增删改查等
	E. 释放资源,归还连接
2、准备工作

MySQL 数据库的代码准备

-- 1. 准备数据库
DROP DATABASE IF EXISTS mydb10;
CREATE DATABASE IF NOT EXISTS mydb10;
USE mydb10;

-- 2. 准备数据表
DROP TABLE IF EXISTS student;
CREATE TABLE IF NOT EXISTS student (
	id INT PRIMARY KEY AUTO_INCREMENT,
	sname VARCHAR(20),
	sage  INT
);

-- 3. 查询表信息
SELECT * FROM student;

配置文件 src/druid.properties

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/mydb10
username=root
password=root
initialSize=5
maxActive=10
maxWait=3000
3、写Java代码
import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.Statement;
import java.util.Properties;

//目标:学习Druid连接池的快速入门
@SuppressWarnings("all")
public class Test01 {

    public static void main(String[] args) throws Exception{
        //1. 获取配置文件的 Properties的对象
        InputStream is = ClassLoader.getSystemResourceAsStream("druid.properties");
        Properties pp = new Properties();
        pp.load(is);
        is.close();
        //2. 通过工厂 DruidDataSorceFactory 获取到连接池 DataSource 的对象
        DataSource ds = DruidDataSourceFactory.createDataSource(pp);
        //3. 拿到连接池的对象之后,就可以获取到连接Connection
        Connection conn = ds.getConnection();
        //4. 获取到操作数据库的对象 Statement 进行SQL操作
        Statement stat = conn.createStatement();
        String sql = "INSERT INTO student VALUES (NULL,'黄杰',18)";
        int lineNumber = stat.executeUpdate(sql);
        System.out.println("lineNumber = " + lineNumber);
        System.out.println(lineNumber>0?"成功":"失败");
        //5. 释放资源, 归还连接
        stat.close();
        conn.close();
    }
}
第04节 工具类
1、工具类定义
public class JDBCUtils {

    private static DataSource ds = null;

    static {
        try {
            Properties pp = new Properties();
            InputStream is = ClassLoader.getSystemResourceAsStream("druid.properties");
            pp.load(is);
            is.close();
            ds = DruidDataSourceFactory.createDataSource(pp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /***
     * 获取到连接的对象
     */
    public static Connection getConnection() {
        Connection conn = null;
        try {
            //预防空指针异常。如果我们的 Properties 内容错误
            if (ds != null) {
                conn = ds.getConnection();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }


    /**
     * 释放资源
     */
    public static void close(Connection conn, Statement stat){
        close(conn,stat,null);
    }

    public static void close(Connection conn, Statement stat, ResultSet resu){
        if (resu!=null){
            try {
                resu.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (stat!=null){
            try {
                stat.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
2、工具类使用
//测试类
@SuppressWarnings("all")
public class Demo {

    @Test
    public void testInsert() throws Exception{
        //获取到连接对象
        Connection conn = JDBCUtils.getConnection();
        Statement stat = conn.createStatement();
        String sql = "INSERT INTO student VALUES (NULL,'定浩',20)";
        int lineNumber = stat.executeUpdate(sql);
        System.out.println("lineNumber = " + lineNumber);
        System.out.println(lineNumber>0?"成功":"失败");
        JDBCUtils.close(conn,stat);

    }

    @Test
    public void testDelete() throws Exception{
        //获取到连接对象
        Connection conn = JDBCUtils.getConnection();
        Statement stat = conn.createStatement();
        String sql = "DELETE FROM student WHERE id=1";
        int lineNumber = stat.executeUpdate(sql);
        System.out.println("lineNumber = " + lineNumber);
        System.out.println(lineNumber>0?"成功":"失败");
        JDBCUtils.close(conn,stat);

    }

    @Test
    public void testUpdate() throws Exception{
        //获取到连接对象
        Connection conn = JDBCUtils.getConnection();
        Statement stat = conn.createStatement();
        String sql = "UPDATE student SET sname = '郭龙' WHERE id=2";
        int lineNumber = stat.executeUpdate(sql);
        System.out.println("lineNumber = " + lineNumber);
        System.out.println(lineNumber>0?"成功":"失败");
        JDBCUtils.close(conn,stat);
    }

    @Test
    public void testSelect() throws Exception{
        //获取到连接对象
        Connection conn = JDBCUtils.getConnection();
        Statement stat = conn.createStatement();
        String sql = "SELECT * FROM student";
        ResultSet resu = stat.executeQuery(sql);
        while (resu.next()){
            int id = resu.getInt("id");
            String name = resu.getString("sname");
            int age = resu.getInt("sage");
            System.out.println(id+"\t"+name+"\t"+age);
        }
        JDBCUtils.close(conn,stat,resu);
    }
}

第二章 Spring工具类

第01节 准备工作
1、导入jar包

JDBC需要使用的jar包

mysql-connector-java-5.1.37-bin.jar

Druid连接池需要使用的jar包

druid-1.0.9.jar

Spring 工具类需要使用的jar包

commons-logging-1.2.jar
spring-beans-5.0.0.RELEASE.jar
spring-core-5.0.0.RELEASE.jar
spring-jdbc-5.0.0.RELEASE.jar
spring-tx-5.0.0.RELEASE.jar
2、准备配置文件

配置文件 src/druid.properties

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/mydb10
username=root
password=root
initialSize=5
maxActive=10
maxWait=3000
3、JDBC工具类
public class JDBCUtils {

    private static DataSource ds = null;

    static {
        try {
            Properties pp = new Properties();
            InputStream is = ClassLoader.getSystemResourceAsStream("druid.properties");
            pp.load(is);
            is.close();
            ds = DruidDataSourceFactory.createDataSource(pp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取到连接池对象的方法
     */
    public static DataSource getDataSource(){
        return ds;
    }


    /***
     * 获取到连接的对象
     */
    public static Connection getConnection() {
        Connection conn = null;
        try {
            //预防空指针异常。如果我们的 Properties 内容错误
            if (ds != null) {
                conn = ds.getConnection();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }


    /**
     * 释放资源
     */
    public static void close(Connection conn, Statement stat){
        close(conn,stat,null);
    }

    public static void close(Connection conn, Statement stat, ResultSet resu){
        if (resu!=null){
            try {
                resu.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (stat!=null){
            try {
                stat.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
第02节 增删改
1、新增操作

基础操作

@Test
public void testInsert(){
    //1.创建到 JdbcTemplate 的对象, 传递参数, 参数是连接池对象
    JdbcTemplate temp = new JdbcTemplate(JDBCUtils.getDataSource());
    //2.执行SQL语句
    String sql = "INSERT INTO student VALUES (NULL,'宇波',21)";
    //3. 执行操作
    int lineNumber = temp.update(sql);
    //4. 预言,断言,判断一下
    Assert.assertEquals(lineNumber,1);
}

预置操作

@Test
public void testInsert(){
    //1.创建到 JdbcTemplate 的对象, 传递参数, 参数是连接池对象
    JdbcTemplate temp = new JdbcTemplate(JDBCUtils.getDataSource());
    //2.执行SQL语句
    String sql = "INSERT INTO student VALUES (NULL,?,?)";
    //3.执行SQL语句的操作
    int lineNumber = temp.update(sql, "志文", 21);
    //4.断言 预言 预测一下结果
    Assert.assertEquals(1,lineNumber);
}
2、删除操作

基础操作

@Test
public void testDelete(){
    //1.创建到 JdbcTemplate 的对象, 传递参数, 参数是连接池对象
    JdbcTemplate temp = new JdbcTemplate(JDBCUtils.getDataSource());
    //2.执行SQL语句
    String sql = "DELETE FROM student WHERE id=2";
    //3. 执行操作
    int lineNumber = temp.update(sql);
    //4. 预言,断言,判断一下
    Assert.assertEquals(lineNumber,1);
}

预置操作

@Test
public void testDelete(){
    //1.创建到 JdbcTemplate 的对象, 传递参数, 参数是连接池对象
    JdbcTemplate temp = new JdbcTemplate(JDBCUtils.getDataSource());
    //2.执行SQL语句
    String sql = "DELETE FROM student WHERE id=?";
    //3.执行SQL语句的操作
    int lineNumber = temp.update(sql, 3);
    //4.断言 预言 预测一下结果
    Assert.assertEquals(1,lineNumber);
}
3、修改操作

基础操作

@Test
public void testUpdate(){
    //1.创建到 JdbcTemplate 的对象, 传递参数, 参数是连接池对象
    JdbcTemplate temp = new JdbcTemplate(JDBCUtils.getDataSource());
    //2.执行SQL语句
    String sql = "UPDATE student SET sname='佑威' WHERE id=3";
    //3. 执行操作
    int lineNumber = temp.update(sql);
    //4. 预言,断言,判断一下
    Assert.assertEquals(lineNumber,1);
}

预置操作

@Test
public void testUpdate(){
    //1.创建到 JdbcTemplate 的对象, 传递参数, 参数是连接池对象
    JdbcTemplate temp = new JdbcTemplate(JDBCUtils.getDataSource());
    //2.执行SQL语句
    String sql = "UPDATE student SET sname=? WHERE id=?";
    //3.执行SQL语句的操作
    int lineNumber = temp.update(sql, "郭龙",4);
    //4.断言 预言 预测一下结果
    Assert.assertEquals(1,lineNumber);
}
第03节 查询操作
1、聚合查询
//queryForObject() 主要用于查询聚合函数
@Test
public void testQueryForObject1() {
    //1. 创建 JdbcTemplate 的对象,参数是数据库连接池
    JdbcTemplate temp = new JdbcTemplate(JDBCUtils.getDataSource());
    //2.准备执行SQL语句,可以准备SQL语句
    String sql = "SELECT COUNT(*) FROM railway";
    //3.查询SQL语句
    Integer count = temp.queryForObject(sql, int.class);
    //4.展示结果
    System.out.println("count = " + count);
}
2、封装集合Bean
//查询结果,封装成为一个List<Bean>的形式
@Test
public void testBeanPropertyRowMapper() {
    //1. 创建 JdbcTemplate 的对象,参数是数据库连接池
    JdbcTemplate temp = new JdbcTemplate(JDBCUtils.getDataSource());
    //2.准备执行SQL语句,可以准备SQL语句
    String sql = "SELECT * FROM railway";
    //3.调用查询的方法
    List<UserBean> mlist = temp.query(sql, new BeanPropertyRowMapper<>(UserBean.class));
    //4.循环遍历
    for (int i = 0; i < mlist.size(); i++) {
        UserBean bean = mlist.get(i);
        System.out.println(i + "," + bean);
    }
}

注意问题:

1、成员变量的名称和表当中的列名,必须保持一致。

2、成员变量的数据类型 和 表当中的数据类型,建议保持一致。

3、封装Map集合
//将查询的结果,封装成为 Map集合。 单一数据的查询,可以封装成为map集合(登录校验)
@Test
public void testQueryForMap(){
    //1. 创建 JdbcTemplate 的对象,参数是数据库连接池
    JdbcTemplate temp = new JdbcTemplate(JDBCUtils.getDataSource());
    //2.准备执行SQL语句,可以准备SQL语句
    String sql = "SELECT * FROM railway WHERE email = ?";
    //3.查询结果,封装成为Map集合
    Map<String, Object> map = temp.queryForMap(sql, "274667266@qq.com");
    //4.循环遍历Map集合
    Set<Map.Entry<String, Object>> entries = map.entrySet();
    for (Map.Entry<String, Object> entry : entries) {
        String key = entry.getKey();
        Object value = entry.getValue();
        System.out.println(key+","+value);
    }
}
4、封装List集合
//将查询的结果,封装成为List<Map<String,Object>> 集合。查询所有的
@Test
public void testQueryForList(){
    //1. 创建 JdbcTemplate 的对象,参数是数据库连接池
    JdbcTemplate temp = new JdbcTemplate(JDBCUtils.getDataSource());
    //2.准备执行SQL语句,可以准备SQL语句
    String sql = "SELECT * FROM railway WHERE NAME LIKE ?";
    //3. 查询结果,封装成为 List<Map<String,Object>> 数据
    List<Map<String, Object>> mList = temp.queryForList(sql, "康%");
    //4. 循环遍历外层的List集合
    for (Map<String, Object> map : mList) {
        //循环遍历Map集合
        Set<Map.Entry<String, Object>> entries = map.entrySet();
        for (Map.Entry<String, Object> entry : entries) {
            String key = entry.getKey();
            Object value = entry.getValue();
            System.out.println(key+","+value);
        }
        System.out.println("=====================");
    }
}

今日总结:

以上两种数据库常用连接池,Druid连接池 必须得熟练掌握,这个是阿里巴巴常用的连接池,支付宝就是用的这个。连接池的作用是啥呢? 我觉得是java连接数据库也就是JDBC的快速开发,简单快捷,使用效率高。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值