【JavaWeb】数据库连接池&JDBCTemplate(22)

引言

  • 不能太死板僵化;
  • 据开学还有33天,我还是没准备好;

知识点总结

在这里插入图片描述

数据库连接池

在以前的代码中我们可以发现,创建连接的过程十分频繁且缓慢;因此我们可以在程序开始前创建足够多的连接,并把这些连接放在一起,组成一个数据库连接池。创建线程的过程是连接池帮我们做好的;今天主要介绍两个主流数据库连接池:
C3P0Druid

C3P0数据库连接池

使用步骤
1.导jar包(百度即可)
在这里插入图片描述
2.定义配置文件
与jar包在一起的解压文件夹中有,复制即可;但是放置路径千万不能错!!!;要放在src目录下。因为是按默认路径读取文件的;
在这里插入图片描述
配置文件解释
在这里插入图片描述
3.创建连接池对象;
4.获取连接;
测试

import java.sql.Connection;
import java.sql.SQLException;

public class Demo01 {
    public static void main(String[] args) throws SQLException {
        DataSource ds=new ComboPooledDataSource();
     //   DataSource ds1=new ComboPooledDataSource();
           //获取连接池对象
        for(int i=1;i<=11;i++){
            Connection ct=ds.getConnection();
            System.out.println(i+": "+ct);
        }

    }
}

超过10个连接会报错
在这里插入图片描述
关闭一个的话,就可以了;
在这里插入图片描述

Druid连接池

Druid是阿里巴巴开源的一个连接池,也很方便高效;
使用步骤
1.导包;
在这里插入图片描述
2.获取配置文件;
这里的路径就随意了,但是要以**.properties**结尾;因为要用Properties集合读取。
3.获取连接池对象;
4.获取连接;
测试


import com.alibaba.druid.pool.DruidDataSource;
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 Demo01 {
    public static void main(String[] args) throws Exception {
        Properties   pt=new Properties();
        InputStream resourceAsStream = Demo01.class.getClassLoader().getResourceAsStream("druid.properties");
        pt.load(resourceAsStream);
        DataSource ds= DruidDataSourceFactory.createDataSource(pt);
        Connection ct=ds.getConnection();
    }
}
==================
这是配置文件 -->druid.proerties
-------------------------
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql:///jdbcdemo
username=root
password=admin
# 初始化连接数量
initialSize=5
# 最大连接数
maxActive=10
# 最大等待时间
maxWait=3000

也可以用工具类来封装关闭和获取配置文件的操作

自定义的DruidUtils类
===================
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
/**
 *
 */
public class DruidUtils {
    private static DataSource ds;
    static {
        try {
            Properties pt=new Properties();
            InputStream resourceAsStream = DruidUtils.class.getClassLoader().getResourceAsStream("druid.properties");
            pt.load(resourceAsStream);
            ds=DruidDataSourceFactory.createDataSource(pt);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 /**
     * 获取连接池对象
     * @return
     */
    public static DataSource getDataSource() {
        return ds;
    }
    /**
     * 获取连接对象
     * @return
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }

    /**
     * 关闭两个资源
     * @param st
     * @param ct
     */
    public static void  Close2(Statement st,Connection ct){
        if(ct!=null){
            try {
                ct.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(st!=null){
            try {
                st.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }/**
     * 关闭两个资源
     * @param st
     * @param ct
     */
    public static void  Close3(ResultSet rs,Statement st, Connection ct){
        if(ct!=null){
            try {
                ct.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(st!=null){
            try {
                st.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}

JdbcTemplate

概述

在JDBC中,能够实现我们的大多数需求了,但是需要我们自己获取连接(Connection),执行sql语句(PreparedStatemnt),释放资源(.close());针对这一情况,Spring框架提供了一个对象JDBCTemplate对象来简化JDBC的开发流程;

使用步骤

1.导包(百度);

spring-beans-4.1.2.RELEASE.jar
spring-core-4.1.2.RELEASE.jar
spring-jdbc-4.1.2.RELEASE.jar
spring-tx-4.1.2.RELEASE.jar
com.springsource.org.apache.commons.logging-1.1.1.jar

2.创建JDBCTemplate对象;

public JdbcTemplate(DataSource dataSource)
创建JdbcTemplate对象,方便执行SQL语句

3.调用方法完成CRUD操作;

1.public int update(final String sql)
用于执行`INSERT`、`UPDATE`、`DELETE`等DML语句。
2.public void execute(final String sql)
execute可以执行所有SQL语句,因为没有返回值,一般用于执行DDL语句。
3.public int query***(String sql)
执行查询语句,返回一个值。

测试

import libs.Student;
import org.junit.Test;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import utils.DruidUtils;

import java.util.List;
import java.util.Map;

public class Demo01 {
    private JdbcTemplate  jtp=new JdbcTemplate(DruidUtils.getDataSource());

    /**
     * 执行insert语句
     */
    @Test
    public  void testinsert() {
          String sql="INSERT INTO `student` (`name`, `id`, `Grade`) VALUES ('曹彦兵', NULL, '33')";
         jtp.update(sql);
          //会自动归还到连接池
    }
    /**
     * 执行update语句
     */
    @Test
    public  void testUdate(){
        String sql="update student set Grade=? where id=?";
        jtp.update(sql,23,12);
        //"?"占位符赋值
    }
    /**
     * 执行delete语句
     */
    @Test
    public void testDelete(){
        String sql="delete from student where name=?";
        jtp.update(sql,"高弟弟");
    }
    /**
     * 查询结果返回为Map对象
     */
    @Test
    public void TestSelect1(){
        String sql="select * from student where Grade=?";
        Map<String, Object> stringObjectMap = jtp.queryForMap(sql, "123");
        System.out.println(stringObjectMap);
        //结果集长度只能为一
    }
    /**
     * 查询结果返回为Object对象
     */
    @Test
    public void TestSelect2(){
        String sql="select * from student";
        List<Map<String, Object>> maps = jtp.queryForList(sql);
        for (Map<String, Object> map : maps) {
            System.out.println(map);
        }
    }
    /**
     * 查询结果返回为自定义对象
     * 注意使用格式为
     * query(sql,new BeanPropertyPowMapper<类型>(类型.class);
     */
    @Test
    public void testSelect3(){
        String sql="select * from student";
List<Student> list=jtp.query(sql,new BeanPropertyRowMapper<Student>(Student.class));
        for (Student student : list) {
            System.out.println(student);
        }
    }
    /**
     * 查询数据条数
     */
    @Test
  public void testcount(){
      String sql="select count(id) from student";
       long num=jtp.queryForObject(sql,long.class);
      System.out.println(num);
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

高冷小伙

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

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

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

打赏作者

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

抵扣说明:

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

余额充值