数据库连接池及Spring JDBC

一.数据库连接池

  1. 概念:其实就是一个容器(集合),存放数据库连接的容器。
    当系统初始化好后,容器被创建,容器中会申请一些连接对象,当用户来访问数据库时,从容器中获取连接对象,用户访问完之后,会将连接对象归还给容器。

  2. 好处:

    1. 节约资源
    2. 用户访问高效
  3. 实现:

    1. 标准接口:DataSource javax.sql包下的

      1. 方法:
        • 获取连接:getConnection()
        • 归还连接:Connection.close()。如果连接对象Connection是从连接池中获取的,那么调用Connection.close()方法,则不会再关闭连接了。而是归还连接
    2. 一般我们不去实现它,有数据库厂商来实现

      1. C3P0:数据库连接池技术
      2. Druid:数据库连接池实现技术,由阿里巴巴提供的
1.c3p0数据库连接池
* 步骤:
		1. 导入jar包 (两个) c3p0-0.9.5.2.jar mchange-commons-java-0.2.12.jar ,
			* 不要忘记导入数据库驱动jar包
		2. 定义配置文件:
			* 名称: c3p0.properties 或者 c3p0-config.xml
			* 路径:直接将文件放在src目录下即可。

		3. 创建核心对象 数据库连接池对象 ComboPooledDataSource
		4. 获取连接: getConnection
* 例:
* c3p0-config.xml
*	<?xml version="1.0"?>
        <c3p0-config>
    <!-- 使用默认的配置读取连接池对象 -->
    <default-config>
    <!-- 连接参数 -->
    <property name="driverClass">com.mysql.cj.jdbc.Driver</property>
    <property name="jdbcUrl">jdbc:mysql://localhost:3306/thing?useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=false&amp;serverTimezone=Hongkong</property>
    <property name="user">root</property>
    <property name="password">123456</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.cj.jdbc.Driver</property>
    <property name="jdbcUrl">jdbc:mysql://localhost:3306/school?useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=false&amp;serverTimezone=Hongkong</property>
    <property name="user">root</property>
    <property name="password">123456</property>
    <!-- 连接池参数 -->
    <property name="initialPoolSize">5</property>
    <property name="maxPoolSize">8</property>
    <property name="checkoutTimeout">1000</property>
</named-config>
</c3p0-config>

C3p0.java
public class C3p0 {
    public static void main(String[] args) throws SQLException {
        //1.创建Combo核心类
        DataSource ds = new ComboPooledDataSource();
        Connection conn = ds.getConnection();
        System.out.println(conn);
    }
}
2.Druid:数据库连接池实现技术,由阿里巴巴提供的
1. 步骤:
		1. 导入jar包 druid-1.0.9.jar
		2. 定义配置文件:
			* 是properties形式的
			* 可以叫任意名称,可以放在任意目录下
		3. 加载配置文件。Properties
		4. 获取数据库连接池对象:通过工厂来来获取  DruidDataSourceFactory
		5. 获取连接:getConnection
2.例:
druid.properties
driverClassName = com.mysql.cj.jdbc.Driver
url = jdbc:mysql://localhost:3306/thing?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Hongkong
username = root
password = 123456
initialSize = 5
maxActive = 10
maxWait = 3000

Druid.java
public class Druid {
    public static void main(String[] args) throws Exception {
        //1.导入jar包
        //2.定义配置文件
        //3.加载配置文件
        Properties properties = new Properties();
        InputStream is = Druid_demo1.class.getClassLoader().getResourceAsStream("druid.properties");
        properties.load(is);
        //获取数据库连接对象
        DataSource ds = DruidDataSourceFactory.createDataSource(properties);
        Connection conn = ds.getConnection();
        System.out.println(conn);
    }
}

二.Spring JDBC

* Spring框架对JDBC的简单封装。提供了一个JDBCTemplate对象简化JDBC的开发
* 步骤:
	1. 导入jar包
	2. 创建JdbcTemplate对象。依赖于数据源DataSource
		* JdbcTemplate template = new JdbcTemplate(ds);

	3. 调用JdbcTemplate的方法来完成CRUD的操作
我们先定义一个JDBCUtils类
提供静态代码块加载配置文件,初始化连接池对象
提供方法
			1. 获取连接方法:通过数据库连接池获取连接
			2. 释放资源
			3. 获取连接池的方法

public class JDBCUtils {
    public static DataSource ds = null;
    static {
        try {
            Properties properties = new Properties();
            InputStream is = Druid_demo1.class.getClassLoader().getResourceAsStream("druid.properties");
            properties.load(is);
            ds = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取连接
     */
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }

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

    public static void close(Statement stat, Connection conn){
        close(null,stat,conn);
    }


    public static void close(ResultSet rs , PreparedStatement pst, Connection conn){
        if(rs != null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }


        if(pst != null){
            try {
                pst.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }


        if(conn != null){
            try {
                conn.close();//归还连接
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void close(ResultSet rs , Statement stat, Connection conn){
        if(rs != null){
            try {
                rs.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();
            }
        }
    }

    /**
     * 获取连接池方法
     */

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

用Spring JDBC 向数据库表里添加一条记录
public class Spring {
    public static void main(String[] args) throws Exception {
        JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDateSource());
        String sql = "insert into student values(?,?,?,?)";
        int count = template.update(sql,"164173336","eryi",21,"男");
        System.out.println(count);
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值