java实现网上购物车的简单功能(二)

2014-11-24 08:17:12 · 作者: · 浏览: 1
g goodsId)

045 {

046 return hm.get(goodsId);

047 }

048

049 //把购物车的东西全部取出来,放入ArrayList里面

050 public ArrayList getAllGoods()

051 {

052 //要知道这个ArrayList是用来放GoodsBean,因为GoodsBean与表相对应,所以可以保存物品的信息

053 ArrayList al = new ArrayList();

054 try {

055 //得到连接

056 ct = new ConnDB().getConn();

057

058 //想一个sql语句,主要是取得goodsId,就可以全部取出来给外面的使用

059 String sql = "select * from goods where goodsId in (";

060 Iterator it = hm.keySet().iterator();

061 while(it.hasNext())

062 {

063 //把goodsId取出来

064 String goodsId = it.next();

065 if(it.hasNext()){

066 sql += goodsId+",";

067 }else{

068 sql += goodsId+")";

069 }

070 }

071

072 //创建ps,上面把sql语句组织好

073 ps = ct.prepareStatement(sql);

074

075 //执行

076 rs = ps.executeQuery();

077

078 //取出来,放在GoodsBean,再把GoodsBean一个个放入ArrayList中,显示的页面就可以调用了

079 while(rs.next())

080 {

081 GoodsBean gb = new GoodsBean();

082 gb.setGoodsId(rs.getInt(1));

083 gb.setGoodsName(rs.getString(2));

084 gb.setGoodsInfo(rs.getString(3));

085 gb.setGoodsPlace(rs.getString(4));

086

087 //把gb放入al,相当于保存了从数据库中获得的数据

088 al.add(gb);

089 }

090 } catch (Exception e) {

091 e.printStackTrace();

092 // TODO: handle exception

093 }finally{

094 this.closeDBResource();

095 }

096 return al;

097 }

098

099 //关闭数据库资源

100 public void closeDBResource()

101 {

102 try {

103 if(rs != null){

104 rs.close();

105 rs = null;

106 }

107 } catch (Exception e2) {

108 e2.printStackTrace();

109 // TODO: handle exception

110 }

111 try {

112 if(ps != null){

113 ps.close();

114 ps = null;

115 }

116 } catch (Exception e2) {

117 e2.printStackTrace();

118 // TODO: handle exception

119 }

120 try {

121 if(ct != null){

122 ct.close();

123 ct= null;

124 }

125 } catch (Exception e2) {

126 e2.printStackTrace();

127 // TODO: handle exception

128 }

129 }

130 }