JDBC连接池 JDBCTemplate

11. 数据库连接池 2 32. Spring JDBC : JDBC Template

数据库连接池

11. 概念:其实就是一个容器(集合),存放数据库连接的容器。 2 当系统初始化好后,容器被创建,容器中会申请一些连接对象,当用户来访问数据库时,从容器中获取连接对象,用户访问完之后,会将连接对象归还给容器。 3 42. 好处: 5 1. 节约资源 6 2. 用户访问高效 7 83. 实现: 9 1. 标准接口:DataSource javax.sql包下的 10 1. 方法: 11 * 获取连接:getConnection() 12 * 归还连接:Connection.close()。如果连接对象Connection是从连接池中获取的,那么调用Connection.close()方法,则不会再关闭连接了。而是归还连接 13 14 2. 一般我们不去实现它,有数据库厂商来实现 15 1. C3P0:数据库连接池技术 16 2. Druid:数据库连接池实现技术,由阿里巴巴提供的 17 184. C3P0:数据库连接池技术 19 * 步骤: 20 1. 导入jar包 (两个) c3p0-0.9.5.2.jar mchange-commons-java-0.2.12.jar21 * 不要忘记导入数据库驱动jar包 22 2. 定义配置文件: 23 * 名称: c3p0.properties 或者 c3p0-config.xml 24 * 路径:直接将文件放在src目录下即可。 25 26 3. 创建核心对象 数据库连接池对象 ComboPooledDataSource 27 4. 获取连接: getConnection 28 * 代码: 29 //1.创建数据库连接池对象 30 DataSource ds = new ComboPooledDataSource(); 31 //2. 获取连接对象 32 Connection conn = ds.getConnection(); 335. Druid:数据库连接池实现技术,由阿里巴巴提供的 34 1. 步骤: 35 1. 导入jar包 druid-1.0.9.jar 36 2. 定义配置文件: 37 * 是properties形式的 38 * 可以叫任意名称,可以放在任意目录下 39 3. 加载配置文件。Properties 40 4. 获取数据库连接池对象:通过工厂来来获取 DruidDataSourceFactory 41 5. 获取连接:getConnection 42 * 代码: 43 //3.加载配置文件 44 Properties pro = new Properties(); 45 InputStream is = DruidDemo.class.getClassLoader().getResourceAsStream("druid.properties"); 46 pro.load(is); 47 //4.获取连接池对象 48 DataSource ds = DruidDataSourceFactory.createDataSource(pro); 49 //5.获取连接 50 Connection conn = ds.getConnection(); 51 2. 定义工具类 52 1. 定义一个类 JDBCUtils 53 2. 提供静态代码块加载配置文件,初始化连接池对象 54 3. 提供方法 55 1. 获取连接方法:通过数据库连接池获取连接 56 2. 释放资源 57 3. 获取连接池的方法 58 59 * 代码: 60 public class JDBCUtils { 61 62 //1.定义成员变量 DataSource 63 private static DataSource ds ; 64 65 static{ 66 try { 67 //1.加载配置文件 68 Properties pro = new Properties(); 69 pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties")); 70 //2.获取DataSource 71 ds = DruidDataSourceFactory.createDataSource(pro); 72 } catch (IOException e) { 73 e.printStackTrace(); 74 } catch (Exception e) { 75 e.printStackTrace(); 76 } 77 } 78 79 /** 80 * 获取连接 81 */ 82 public static Connection getConnection() throws SQLException { 83 return ds.getConnection(); 84 } 85 86 /** 87 * 释放资源 88 */ 89 public static void close(Statement stmt,Connection conn){ 90 /* if(stmt != null){ 91 try { 92 stmt.close(); 93 } catch (SQLException e) { 94 e.printStackTrace(); 95 } 96 } 97 98 if(conn != null){ 99 try { 100 conn.close();//归还连接 101 } catch (SQLException e) { 102 e.printStackTrace(); 103 } 104 }*/ 105 106 close(null,stmt,conn); 107 } 108 109 public static void close(ResultSet rs , Statement stmt, Connection conn){ 110 111 if(rs != null){ 112 try { 113 rs.close(); 114 } catch (SQLException e) { 115 e.printStackTrace(); 116 } 117 } 118 119 if(stmt != null){ 120 try { 121 stmt.close(); 122 } catch (SQLException e) { 123 e.printStackTrace(); 124 } 125 } 126 127 if(conn != null){ 128 try { 129 conn.close();//归还连接 130 } catch (SQLException e) { 131 e.printStackTrace(); 132 } 133 } 134 } 135 136 /** 137 * 获取连接池方法 138 */ 139 140 public static DataSource getDataSource(){ 141 return ds; 142 } 143 144 }

Spring JDBC

1* Spring框架对JDBC的简单封装。提供了一个JDBCTemplate对象简化JDBC的开发 2* 步骤: 3 1. 导入jar包 4 2. 创建JdbcTemplate对象。依赖于数据源DataSource 5 * JdbcTemplate template = new JdbcTemplate(ds); 6 7 3. 调用JdbcTemplate的方法来完成CRUD的操作 8 * update():执行DML语句。增、删、改语句 9 * queryForMap():查询结果将结果集封装为map集合,将列名作为key,将值作为value 将这条记录封装为一个map集合 10 * 注意:这个方法查询的结果集长度只能是1 11 * queryForList():查询结果将结果集封装为list集合 12 * 注意:将每一条记录封装为一个Map集合,再将Map集合装载到List集合中 13 * query():查询结果,将结果封装为JavaBean对象 14 * query的参数:RowMapper 15 * 一般我们使用BeanPropertyRowMapper实现类。可以完成数据到JavaBean的自动封装 16 * new BeanPropertyRowMapper<类型>(类型.class) 17 * queryForObject:查询结果,将结果封装为对象 18 * 一般用于聚合函数的查询 19 20 4. 练习: 21 * 需求: 22 1. 修改1号数据的 salary 为 10000 23 2. 添加一条记录 24 3. 删除刚才添加的记录 25 4. 查询id为1的记录,将其封装为Map集合 26 5. 查询所有记录,将其封装为List 27 6. 查询所有记录,将其封装为Emp对象的List集合 28 7. 查询总记录数 29 30 * 代码: 31 32 import cn.itcast.domain.Emp; 33 import cn.itcast.utils.JDBCUtils; 34 import org.junit.Test; 35 import org.springframework.jdbc.core.BeanPropertyRowMapper; 36 import org.springframework.jdbc.core.JdbcTemplate; 37 import org.springframework.jdbc.core.RowMapper; 38 39 import java.sql.Date; 40 import java.sql.ResultSet; 41 import java.sql.SQLException; 42 import java.util.List; 43 import java.util.Map; 44 45 public class JdbcTemplateDemo2 { 46 47 //Junit单元测试,可以让方法独立执行 48 49 //1. 获取JDBCTemplate对象 50 private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource()); 51 /** 52 * 1. 修改1号数据的 salary 为 10000 53 */ 54 @Test 55 public void test1(){ 56 57 //2. 定义sql 58 String sql = "update emp set salary = 10000 where id = 1001"; 59 //3. 执行sql 60 int count = template.update(sql); 61 System.out.println(count); 62 } 63 64 /** 65 * 2. 添加一条记录 66 */ 67 @Test 68 public void test2(){ 69 String sql = "insert into emp(id,ename,dept_id) values(?,?,?)"; 70 int count = template.update(sql, 1015, "郭靖", 10); 71 System.out.println(count); 72 73 } 74 75 /** 76 * 3.删除刚才添加的记录 77 */ 78 @Test 79 public void test3(){ 80 String sql = "delete from emp where id = ?"; 81 int count = template.update(sql, 1015); 82 System.out.println(count); 83 } 84 85 /** 86 * 4.查询id为1001的记录,将其封装为Map集合 87 * 注意:这个方法查询的结果集长度只能是1 88 */ 89 @Test 90 public void test4(){ 91 String sql = "select * from emp where id = ? or id = ?"; 92 Map<String, Object> map = template.queryForMap(sql, 1001,1002); 93 System.out.println(map); 94 //{id=1001, ename=孙悟空, job_id=4, mgr=1004, joindate=2000-12-17, salary=10000.00, bonus=null, dept_id=20} 95 96 } 97 98 /** 99 * 5. 查询所有记录,将其封装为List 100 */ 101 @Test 102 public void test5(){ 103 String sql = "select * from emp"; 104 List<Map<String, Object>> list = template.queryForList(sql); 105 106 for (Map<String, Object> stringObjectMap : list) { 107 System.out.println(stringObjectMap); 108 } 109 } 110 111 /** 112 * 6. 查询所有记录,将其封装为Emp对象的List集合 113 */ 114 115 @Test 116 public void test6(){ 117 String sql = "select * from emp"; 118 List<Emp> list = template.query(sql, new RowMapper<Emp>() { 119 120 @Override 121 public Emp mapRow(ResultSet rs, int i) throws SQLException { 122 Emp emp = new Emp(); 123 int id = rs.getInt("id"); 124 String ename = rs.getString("ename"); 125 int job_id = rs.getInt("job_id"); 126 int mgr = rs.getInt("mgr"); 127 Date joindate = rs.getDate("joindate"); 128 double salary = rs.getDouble("salary"); 129 double bonus = rs.getDouble("bonus"); 130 int dept_id = rs.getInt("dept_id"); 131 132 emp.setId(id); 133 emp.setEname(ename); 134 emp.setJob_id(job_id); 135 emp.setMgr(mgr); 136 emp.setJoindate(joindate); 137 emp.setSalary(salary); 138 emp.setBonus(bonus); 139 emp.setDept_id(dept_id); 140 141 return emp; 142 } 143 }); 144 145 for (Emp emp : list) { 146 System.out.println(emp); 147 } 148 } 149 150 /** 151 * 6. 查询所有记录,将其封装为Emp对象的List集合 152 */ 153 154 @Test 155 public void test6_2(){ 156 String sql = "select * from emp"; 157 List<Emp> list = template.query(sql, new BeanPropertyRowMapper<Emp>(Emp.class)); 158 for (Emp emp : list) { 159 System.out.println(emp); 160 } 161 } 162 163 /** 164 * 7. 查询总记录数 165 */ 166 167 @Test 168 public void test7(){ 169 String sql = "select count(id) from emp"; 170 Long total = template.queryForObject(sql, Long.class); 171 System.out.println(total); 172 } 173 }
点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )