6:JDBC连接池&JDBCTemplate

  1 # 今日内容
  2     1. 数据库连接池
  3 
  4     2. Spring JDBC : JDBC Template
  5 
  6 
  7 
  8 ## 数据库连接池
  9     1. 概念:其实就是一个容器(集合),存放数据库连接的容器。
 10             当系统初始化好后,容器被创建,容器中会申请一些连接对象,当用户来访问数据库时,从容器中获取连接对象,用户访问完之后,会将连接对象归还给容器。
 11 
 12     2. 好处:
 13         1. 节约资源
 14         2. 用户访问高效
 15 
 16     3. 实现:
 17         1. 标准接口:DataSource   javax.sql包下的
 18             1. 方法:
 19                 * 获取连接:getConnection()
 20                 * 归还连接:Connection.close()。如果连接对象Connection是从连接池中获取的,那么调用Connection.close()方法,则不会再关闭连接了。而是归还连接
 21 
 22         2. 一般我们不去实现它,有数据库厂商来实现
 23             1. C3P0:数据库连接池技术
 24             2. Druid:数据库连接池实现技术,由阿里巴巴提供的
 25 
 26 
 27     4. C3P0:数据库连接池技术
 28         * 步骤:
 29             1. 导入jar包 (两个) c3p0-0.9.5.2.jar mchange-commons-java-0.2.12.jar ,
 30                 * 不要忘记导入数据库驱动jar包
 31             2. 定义配置文件:
 32                 * 名称: c3p0.properties 或者 c3p0-config.xml
 33                 * 路径:直接将文件放在src目录下即可。
 34 
 35             3. 创建核心对象 数据库连接池对象 ComboPooledDataSource
 36             4. 获取连接: getConnection
 37         * 代码:
 38              //1.创建数据库连接池对象
 39             DataSource ds  = new ComboPooledDataSource();
 40             //2. 获取连接对象
 41             Connection conn = ds.getConnection();
 42     5. Druid:数据库连接池实现技术,由阿里巴巴提供的
 43         1. 步骤:
 44             1. 导入jar包 druid-1.0.9.jar
 45             2. 定义配置文件:
 46                 * 是properties形式的
 47                 * 可以叫任意名称,可以放在任意目录下
 48             3. 加载配置文件。Properties
 49             4. 获取数据库连接池对象:通过工厂来来获取  DruidDataSourceFactory
 50             5. 获取连接:getConnection
 51         * 代码:
 52              //3.加载配置文件
 53             Properties pro = new Properties();
 54             InputStream is = DruidDemo.class.getClassLoader().getResourceAsStream("druid.properties");
 55             pro.load(is);
 56             //4.获取连接池对象
 57             DataSource ds = DruidDataSourceFactory.createDataSource(pro);
 58             //5.获取连接
 59             Connection conn = ds.getConnection();
 60         2. 定义工具类
 61             1. 定义一个类 JDBCUtils
 62             2. 提供静态代码块加载配置文件,初始化连接池对象
 63             3. 提供方法
 64                 1. 获取连接方法:通过数据库连接池获取连接
 65                 2. 释放资源
 66                 3. 获取连接池的方法
 67 
 68 
 69         * 代码:
 70             public class JDBCUtils {
 71 
 72                 //1.定义成员变量 DataSource
 73                 private static DataSource ds ;
 74             
 75                 static{
 76                     try {
 77                         //1.加载配置文件
 78                         Properties pro = new Properties();
 79                         pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
 80                         //2.获取DataSource
 81                         ds = DruidDataSourceFactory.createDataSource(pro);
 82                     } catch (IOException e) {
 83                         e.printStackTrace();
 84                     } catch (Exception e) {
 85                         e.printStackTrace();
 86                     }
 87                 }
 88             
 89                 /**
 90                  * 获取连接
 91                  */
 92                 public static Connection getConnection() throws SQLException {
 93                     return ds.getConnection();
 94                 }
 95             
 96                 /**
 97                  * 释放资源
 98                  */
 99                 public static void close(Statement stmt,Connection conn){
100                    /* if(stmt != null){
101                         try {
102                             stmt.close();
103                         } catch (SQLException e) {
104                             e.printStackTrace();
105                         }
106                     }
107             
108                     if(conn != null){
109                         try {
110                             conn.close();//归还连接
111                         } catch (SQLException e) {
112                             e.printStackTrace();
113                         }
114                     }*/
115             
116                    close(null,stmt,conn);
117                 }
118             
119             
120                 public static void close(ResultSet rs , Statement stmt, Connection conn){
121             
122             
123                     if(rs != null){
124                         try {
125                             rs.close();
126                         } catch (SQLException e) {
127                             e.printStackTrace();
128                         }
129                     }
130             
131             
132                     if(stmt != null){
133                         try {
134                             stmt.close();
135                         } catch (SQLException e) {
136                             e.printStackTrace();
137                         }
138                     }
139             
140                     if(conn != null){
141                         try {
142                             conn.close();//归还连接
143                         } catch (SQLException e) {
144                             e.printStackTrace();
145                         }
146                     }
147                 }
148             
149                 /**
150                  * 获取连接池方法
151                  */
152             
153                 public static DataSource getDataSource(){
154                     return  ds;
155                 }
156             
157             }
158 
159 ## Spring JDBC
160     * Spring框架对JDBC的简单封装。提供了一个JDBCTemplate对象简化JDBC的开发
161     * 步骤:
162         1. 导入jar包
163         2. 创建JdbcTemplate对象。依赖于数据源DataSource
164             * JdbcTemplate template = new JdbcTemplate(ds);
165 
166         3. 调用JdbcTemplate的方法来完成CRUD的操作
167             * update():执行DML语句。增、删、改语句
168             * queryForMap():查询结果将结果集封装为map集合,将列名作为key,将值作为value 将这条记录封装为一个map集合
169                 * 注意:这个方法查询的结果集长度只能是1
170             * queryForList():查询结果将结果集封装为list集合
171                 * 注意:将每一条记录封装为一个Map集合,再将Map集合装载到List集合中
172             * query():查询结果,将结果封装为JavaBean对象
173                 * query的参数:RowMapper
174                     * 一般我们使用BeanPropertyRowMapper实现类。可以完成数据到JavaBean的自动封装
175                     * new BeanPropertyRowMapper<类型>(类型.class)
176             * queryForObject:查询结果,将结果封装为对象
177                 * 一般用于聚合函数的查询
178 
179         4. 练习:
180             * 需求:
181                 1. 修改1号数据的 salary 为 10000
182                 2. 添加一条记录
183                 3. 删除刚才添加的记录
184                 4. 查询id为1的记录,将其封装为Map集合
185                 5. 查询所有记录,将其封装为List
186                 6. 查询所有记录,将其封装为Emp对象的List集合
187                 7. 查询总记录数
188 
189             * 代码:
190                 
191                 import cn.itcast.domain.Emp;
192                 import cn.itcast.utils.JDBCUtils;
193                 import org.junit.Test;
194                 import org.springframework.jdbc.core.BeanPropertyRowMapper;
195                 import org.springframework.jdbc.core.JdbcTemplate;
196                 import org.springframework.jdbc.core.RowMapper;
197                 
198                 import java.sql.Date;
199                 import java.sql.ResultSet;
200                 import java.sql.SQLException;
201                 import java.util.List;
202                 import java.util.Map;
203                 
204                 public class JdbcTemplateDemo2 {
205                 
206                     //Junit单元测试,可以让方法独立执行
207                 
208                 
209                     //1. 获取JDBCTemplate对象
210                     private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
211                     /**
212                      * 1. 修改1号数据的 salary 为 10000
213                      */
214                     @Test
215                     public void test1(){
216                 
217                         //2. 定义sql
218                         String sql = "update emp set salary = 10000 where id = 1001";
219                         //3. 执行sql
220                         int count = template.update(sql);
221                         System.out.println(count);
222                     }
223                 
224                     /**
225                      * 2. 添加一条记录
226                      */
227                     @Test
228                     public void test2(){
229                         String sql = "insert into emp(id,ename,dept_id) values(?,?,?)";
230                         int count = template.update(sql, 1015, "郭靖", 10);
231                         System.out.println(count);
232                 
233                     }
234                 
235                     /**
236                      * 3.删除刚才添加的记录
237                      */
238                     @Test
239                     public void test3(){
240                         String sql = "delete from emp where id = ?";
241                         int count = template.update(sql, 1015);
242                         System.out.println(count);
243                     }
244                 
245                     /**
246                      * 4.查询id为1001的记录,将其封装为Map集合
247                      * 注意:这个方法查询的结果集长度只能是1
248                      */
249                     @Test
250                     public void test4(){
251                         String sql = "select * from emp where id = ? or id = ?";
252                         Map<String, Object> map = template.queryForMap(sql, 1001,1002);
253                         System.out.println(map);
254                         //{id=1001, ename=孙悟空, job_id=4, mgr=1004, joindate=2000-12-17, salary=10000.00, bonus=null, dept_id=20}
255                 
256                     }
257                 
258                     /**
259                      * 5. 查询所有记录,将其封装为List
260                      */
261                     @Test
262                     public void test5(){
263                         String sql = "select * from emp";
264                         List<Map<String, Object>> list = template.queryForList(sql);
265                 
266                         for (Map<String, Object> stringObjectMap : list) {
267                             System.out.println(stringObjectMap);
268                         }
269                     }
270                 
271                     /**
272                      * 6. 查询所有记录,将其封装为Emp对象的List集合
273                      */
274                 
275                     @Test
276                     public void test6(){
277                         String sql = "select * from emp";
278                         List<Emp> list = template.query(sql, new RowMapper<Emp>() {
279                 
280                             @Override
281                             public Emp mapRow(ResultSet rs, int i) throws SQLException {
282                                 Emp emp = new Emp();
283                                 int id = rs.getInt("id");
284                                 String ename = rs.getString("ename");
285                                 int job_id = rs.getInt("job_id");
286                                 int mgr = rs.getInt("mgr");
287                                 Date joindate = rs.getDate("joindate");
288                                 double salary = rs.getDouble("salary");
289                                 double bonus = rs.getDouble("bonus");
290                                 int dept_id = rs.getInt("dept_id");
291                 
292                                 emp.setId(id);
293                                 emp.setEname(ename);
294                                 emp.setJob_id(job_id);
295                                 emp.setMgr(mgr);
296                                 emp.setJoindate(joindate);
297                                 emp.setSalary(salary);
298                                 emp.setBonus(bonus);
299                                 emp.setDept_id(dept_id);
300                 
301                                 return emp;
302                             }
303                         });
304                 
305                 
306                         for (Emp emp : list) {
307                             System.out.println(emp);
308                         }
309                     }
310                 
311                     /**
312                      * 6. 查询所有记录,将其封装为Emp对象的List集合
313                      */
314                 
315                     @Test
316                     public void test6_2(){
317                         String sql = "select * from emp";
318                         List<Emp> list = template.query(sql, new BeanPropertyRowMapper<Emp>(Emp.class));
319                         for (Emp emp : list) {
320                             System.out.println(emp);
321                         }
322                     }
323                 
324                     /**
325                      * 7. 查询总记录数
326                      */
327                 
328                     @Test
329                     public void test7(){
330                         String sql = "select count(id) from emp";
331                         Long total = template.queryForObject(sql, Long.class);
332                         System.out.println(total);
333                     }
334                 
335                 }

 

posted @ 2020-08-24 14:31  佛祖让我来巡山  阅读(150)  评论(0编辑  收藏  举报

佛祖让我来巡山博客站 - 创建于 2018-08-15

开发工程师个人站,内容主要是网站开发方面的技术文章,大部分来自学习或工作,部分来源于网络,希望对大家有所帮助。

Bootstrap中文网