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.jar ,
21 * 不要忘记导入数据库驱动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 81
82 public static Connection getConnection() throws SQLException {
83 return ds.getConnection();
84 }
85
86 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 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 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 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 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 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 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 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 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 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 }