📄 shoppingcartimpl.java
字号:
package com.tarena.dao.ipml;import java.sql.Connection;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.ArrayList;import java.util.HashSet;import java.util.Iterator;import java.util.List;import com.tarena.util.*;import com.tarena.dao.ShoppingCartDao;import com.tarena.entity.Item;import com.tarena.entity.Order;import com.tarena.entity.Product;public class ShoppingCartImpl implements ShoppingCartDao{ /* * 生成帐单,返回帐单号 * */ public long generateOrder(Order order) { Connection con=null; Statement st=null; ResultSet rs=null; con=JdbcUtil.getConnection(); try { st=con.createStatement(); /* * 帐单存入数据库,得到帐单号 * 帐单号在数据表中为主键,设为auto_increment,自动插入记录 * */ Long orderId=null; double orderCost=order.getCost(); Long uid=order.getUser().getOid(); String sql="insert into orders(cost,uid) values('"+orderCost+"','"+uid+"')"; st.executeUpdate(sql,Statement.RETURN_GENERATED_KEYS); /* * 设置Statement的executeUpdate方法参数,使其能返回刚才插入数据库 * 的内容的主键值,即帐单号 * */ rs=st.getGeneratedKeys(); if(rs.next()){ orderId=rs.getLong(1); } /* * 将帐单中的条目存入数据库 * */ List items=order.getItems(); Iterator it=items.iterator(); while(it.hasNext()){ Item item=(Item) it.next(); Integer pid=item.getProduct().getId(); int number=item.getNumber(); double cost=item.getCost(); String sql1="insert into item(pid,number,cost,orderid) values('"+pid+"','"+number+"','"+cost+"','"+orderId+"')"; st.executeUpdate(sql1); } return orderId; } catch (SQLException e) { e.printStackTrace(); }finally{ JdbcUtil.release(rs, st, con); } return 0; } /* * 列出商品 * */ public List listProduct() { List<Product> list=new ArrayList(); Connection con=null; Statement st=null; ResultSet rs=null; con=JdbcUtil.getConnection(); String sql="select * from product_bo"; try { st=con.createStatement(); rs=st.executeQuery(sql); while(rs.next()){ Product p=new Product(); p.setId(rs.getInt(1)); p.setName(rs.getString(2)); p.setDescription(rs.getString(3)); p.setPrice(rs.getDouble(4)); list.add(p); } return list; } catch (SQLException e) { e.printStackTrace(); return null; }finally{ JdbcUtil.release(rs, st, con); } /* * 根据商品号得到商品 * */ } public Product getProduct(int productId) { Connection con=null; Statement st=null; ResultSet rs=null; con=JdbcUtil.getConnection(); try { st=con.createStatement(); String sql="select * from product_bo where id="+productId; rs=st.executeQuery(sql); Product p=new Product(); if(rs.next()){ p.setId(rs.getInt(1)); p.setName(rs.getString(2)); p.setDescription(rs.getString(3)); p.setPrice(rs.getDouble(4)); return p; } } catch (SQLException e) { e.printStackTrace(); return null; }finally{ JdbcUtil.release(rs, st, con); } return null; } }
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -