zoukankan      html  css  js  c++  java
  • 关于从数据库连接池中获取链接后的关闭问题

    数据库连接池中关闭连接其实就是把连接归还给数据库连接池当中
    1、不管是否出现异常,finally块中代码都会执行;
    2、当try和catch中有return时,finally仍然会执行;
    3、finally是在return后面的表达式运算后执行的(此时并没有返回运算后的值,而是先把要返回的值保存起来,管finally中的代码怎么样,返回的值都不会改变,任然是之前保存的值),所以函数返回值是在finally执行前确定的;
    4、finally中最好不要包含return,否则程序会提前退出,返回值不是try或catch中保存的返回值。
    代码片段:

     public String CreatOrder(Cart cart, Integer userId) {
            Connection conn=null;
            String orderId=null;
            try {
                conn= DButil.getConnection();
    
            //每次生成一个订单就会同时生成一个商品项同一个id
    
            //订单号是唯一的:时间戳+userId
            orderId=System.currentTimeMillis()+""+userId;
            //生成一个订单对象
            Order order =new Order(orderId,new Date(),cart.getTotalPrice(),0,userId);
            //订单保存在数据库中
            orderDao.saveOrder(conn,order);
    
            //遍历购物车中每一个商品项转化为订单项
            for (Map.Entry<Integer, CartItem>entry: cart.getItems().entrySet()){
    
                CartItem cartItem =entry.getValue();//拿到每一个商品项
                OrderItem orderItem =new OrderItem(null,cartItem.getName(),cartItem.getCount(),cartItem.getPrice(),cartItem.getTotalPrice(),orderId);
                orderItemDao.saveOrderItem(conn,orderItem);
    
              Book book = bookDao.queryBookById(conn,cartItem.getId());
              book.setSales(book.getSales()+cartItem.getCount());
              book.setStock(book.getStock()-cartItem.getCount());
              bookDao.updateBook(conn,book);
            }
            cart.clear();
            return orderId;
            } catch (SQLException e) {
                e.printStackTrace();
            }finally {
            //此时关闭连接,
                DButil.close(conn,null);
            }
            return orderId;
        }
    
  • 相关阅读:
    支付宝生活号授权获取用户信息
    jQuery选项卡
    多图上传加验证加修改file样式
    微信小程序上传图片单张
    圣诞节的整理前两周的内容5
    圣诞节的整理前两周的内容4
    圣诞节的整理前两周的内容3
    圣诞节的整理前两周的内容2
    圣诞节的整理前两周的内容1
    2018.12.14——函数作用域
  • 原文地址:https://www.cnblogs.com/qxsong/p/14321075.html
Copyright © 2011-2022 走看看