Java 数据库连接池 与 JdbcTemplate

本文介绍了数据库连接池的概念,重点讲解了C3P0和Druid两种连接池的配置与使用,包括导入jar包、配置文件设置及连接获取。同时,提到了Spring框架中的JdbcTemplate,作为简化JDBC操作的工具,展示了其如何进行数据库操作。通过连接池和JdbcTemplate,可以有效管理和优化数据库连接,提高系统效率。
摘要由CSDN通过智能技术生成

数据库连接池


  • 程序启动时建立足够的数据库连接,并将这些连接组成一个连接池,由程序动态地对池中的连接进行申请,使用,释放。

  • 当系统初始化时 容器被创建 并申请一些连接对象 当用户来访问数据库时,从容器中获取连接对象,使用完毕后 归还给连接池 不像之前那样每次访问数据库先建立连接 访问完毕后 再释放资源断开连接

  • 有效节约资源 ,提升效率

  • 实现: 标准接口 DataSource javax.sql包下

    • 获取连接: getConnection()
    • 归还 connection.close() 并没有关闭 只是归还
    • 数据库厂商实现
      • c3p0:
      • Druid: 阿里巴巴 性能很高
  • C3P0使用

    • 1.导入jar包 先导入之前的mysql连接的jar包 + 链接中的两个jar包

      「mchange-commons-java-0.2.12.jar」https://www.aliyundrive.com/s/5XAfE8qLNjH
      点击链接保存,或者复制本段内容,打开「阿里云盘」APP ,无需下载极速在线查看,视频原画倍速播放。
      
    • 2.定义配置文件

      • 名称: c3p0.properties 或 c3p0-config.xml

        <c3p0-config>
          <!-- 使用默认的配置读取连接池对象 -->
          <default-config>
          	<!--  连接参数  修改此处4个信息即可 -->
            <property name="driverClass">com.mysql.jdbc.Driver</property>
            <property name="jdbcUrl">jdbc:mysql://localhost:3306/mydb1</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"></property>
            <property name="jdbcUrl"></property>
            <property name="user"></property>
            <property name="password"></property>
            
            <!-- 连接池参数 -->
            <property name="initialPoolSize">5</property>
            <property name="maxPoolSize">8</property>
            <property name="checkoutTimeout">1000</property>
          </named-config>
        </c3p0-config>
        
      • 放在src目录下

      • 注意: 不用去加载配置文件 c3p0会自动去类路径下寻找并加载

    • 3.创建数据库连接池对象 ComboPooledDataSource

    • 4.获取链接 getConnection

    • import com.mchange.v2.c3p0.ComboPooledDataSource;
      
      import javax.sql.DataSource;
      import java.sql.Connection;
      import java.sql.SQLException;
      
      public class C3p0Demo1 {
          public static void main(String[] args) throws SQLException {
              DataSource ds=new ComboPooledDataSource();
              Connection conn = ds.getConnection();
              System.out.println(conn);
          }
      }
      
  • Druid使用

    • 1.导入jar包

      「druid」https://www.aliyundrive.com/s/DFogqHtnGQx
      点击链接保存,或者复制本段内容,打开「阿里云盘」APP ,无需下载极速在线查看,视频原画倍速播放。
      
    • 2.配置文件

      • Druid.properties

      • 可以叫任意名称 放在任意路径下 需要手动加载

        driverClassName=com.mysql.jdbc.Driver
        url=jdbc:mysql://127.0.0.1:3306/mydb1
        username=root
        password=root
        initialSize=5
        maxActive=10
        maxWait=3000
        
    • 3.获取数据库连接池对象 DruidDataSourceFactory 工厂类获取

    • 4.获取连接对象

      import com.alibaba.druid.pool.DruidDataSourceFactory;
      
      import javax.sql.DataSource;
      import java.io.IOException;
      import java.io.InputStream;
      import java.sql.Connection;
      import java.util.Properties;
      
      public class DruidDemo01 {
          public static void main(String[] args) throws Exception {
              //1.导入jar包
              //2.定义配置文件
              //3.加载配置文件
              Properties pro=new Properties();
              InputStream is = DruidDemo01.class.getClassLoader().getResourceAsStream("druid.properties");
              pro.load(is);
              //4.获取数据库连接对象
              DataSource ds = DruidDataSourceFactory.createDataSource(pro);
              Connection conn = ds.getConnection();
              System.out.println(conn);
          }
      }
      
      
    • 5.编写工具类简化Druid书写

      import com.alibaba.druid.pool.DruidDataSourceFactory;
      
      import javax.sql.DataSource;
      import javax.swing.plaf.nimbus.State;
      import java.io.IOException;
      import java.sql.Connection;
      import java.sql.ResultSet;
      import java.sql.SQLException;
      import java.sql.Statement;
      import java.util.Properties;
      
      public class JdbcUtils {
          private static DataSource ds;
      
          public static DataSource getDs() {
              return ds;
          }
      
          public static void setDs(DataSource ds) {
              JdbcUtils.ds = ds;
          }
      
          static{
      
              try {
                  Properties pro=new Properties();
                  pro.load(JdbcUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
                  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 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 void close(Statement stat,Connection conn){
              close(null,stat,conn);
          }
      
      }
      

JDBCTemplate


  • Spring框架对JDBC的简单封装 简化JDBC开发

  • 使用

    • 1.导入jar包

      JDBCTemplate」https://www.aliyundrive.com/s/cVb3Tif9QFu
      点击链接保存,或者复制本段内容,打开「阿里云盘」APP ,无需下载极速在线查看,视频原画倍速播放。
      
    • 2.创建JdbcTemplate对象.依赖于DataSource

    • 3.调用JdbcTemplate的方法完成CRUD操作

      • update()
      • queryForMap()
      • queryForList()
      • query()
      • queryForObject()
    • import com.java.jdbc.utils.JdbcUtils;
      import org.springframework.jdbc.core.JdbcTemplate;
      
      public class JdbcTemplateDemo01 {
          public static void main(String[] args) {
              JdbcTemplate template=new JdbcTemplate(JdbcUtils.getDs());
              String sql="update student set age=5001 where id =?";
              int count = template.update(sql, 4);//传入参数和问号顺序一一对应
              System.out.println(count);//不需要手动释放资源
          }
      }
      
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

怡人蝶梦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值