JDBC连接池 和 JDBC Template

JDBC连接池 和 JDBC Template_第1张图片

每一次 web 请求都要建立一次数据库连接。大型电子商务网站,同时有几千人在线是很正常的事。在这种情况下,频繁的进行数据库连接与断开会造成性能低下。

java中规定的数据库连接池接口:DataSource。由数据库厂商来实现,常用的数据库连接池实现有:C3P0 和 Druid。

数据库连接池使用步骤:
  • 导 jar 包
  • 设置或加载配置文件
    • C3P0
      名称: c3p0.properties 或者 c3p0-config.xml
      路径:src目录下。会自动加载,只需按需修改配置文件中对于池对象参数的设置。
      需要复习一下参数的意义。
    • Druid
      properties类型,可以叫任意名称,可以放在任意目录下 (所以不会自动加载了)。
      需要利用Properties类加载配置文件。推荐放在src目录下,用类加载器就能方便的找到,因此参数不用管文件路径,只要文件名字即可。
  • 创建池对象
    • C3P0
      DataSource ds = new ComboPooledDataSource(); 空参就使用默认配置。传字符串表示使用配置文件中的其他配置。
    • Druid
      DataSource ds = DruidDataSourceFactory.createDataSource(pro); pro就是个集合。
  • 从池对象中获取数据库连接对象:Connection conn = ds.getConnection();

利用工具类 JDBCUtils 对上述步骤进行封装:

public class JDBCUtils {

    //1.定义成员变量 DataSource
    private static DataSource ds ;

    //利用静态代码创建一个池对象。有了数据库连接池,就不存在注册驱动的问题了。
    static{
        try {
            //1.加载配置文件
            Properties pro = new Properties();
            pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
            //2.获取DataSource
            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(Statement stmt,Connection conn){

       close(null,stmt,conn);
    }


    public static void close(ResultSet rs , Statement stmt, Connection conn){


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


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

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

    /**
     * 获取连接池
     */

    public static DataSource getDataSource() {
        return  ds;
    }

}

Spring JDBC

针对 JDBCUtils 简化不了的,SQL操作的部分,进行自动化处理。

  • 导入jar包
  • 创建JdbcTemplate对象。依赖于数据源DataSource
    JdbcTemplate template = new JdbcTemplate(ds);
  • 调用JdbcTemplate的方法来完成SQL操作
    • 增删改:update(String sql, sql中的参数)
      String sql = "insert into emp(id,ename,dept_id) values(?,?,?)";
      int count = template.update(sql, 1015, "郭靖", 10); //传参比 PreparedStatement 简单
      
    • 查:
      精华:把结果集自动封装成对象。
      • 行数据 --> Map,列名为key,值为value:
        一行:Map queryForMap(String sql, sql中的参数)
        多行:List> queryForList(String sql, sql中的参数)
      • 行数据 --> T对象:List query(String sql, sql中的参数, RowMapper rm)
        自己决定映射方式:使用 RowMapper,重写其方法实现结果集到对象的映射
        String sql = "select * from emp";
        List list = template.query(sql, new RowMapper() {
        
          @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);
        }
        
        利用字节码文件自动映射:List query(String sql, sql中的参数, BeanPropertyRowMapper bprm)
        BeanPropertyRowMapper的意思:数据表的行映射为Java Bean对象的属性
        String sql = "select * from emp";
        List list = template.query(sql, new BeanPropertyRowMapper (Emp.class));
        for (Emp emp : list) {
          System.out.println(emp);
        }
        
      • 聚合函数:queryForObject()
        String sql = "select count(id) from emp";
        Long total = template.queryForObject(sql, Long.class);
        

你可能感兴趣的:(JDBC连接池 和 JDBC Template)