dao层:
接口:
public interface ShopDao { public List<Shop> queryAllShop(Connection con) throws Exception; }
实现:
public class ShopDaoImpl implements ShopDao{ @Override public List<Shop> queryAllShop(Connection con) throws Exception { List<Shop> list=new ArrayList<Shop>(); PreparedStatement ps=null; ResultSet rs=null; try{ String sql="select sid,sname,price,intro from shop"; ps=con.prepareStatement(sql); rs=ps.executeQuery(); while (rs.next()){ Shop s=new Shop(); s.setSid(rs.getInt("sid")); s.setSname(rs.getString("sname")); s.setPrice(rs.getDouble("price")); s.setIntro(rs.getString("intro")); System.out.println(s); list.add(s); } }finally { JDBCUtil.close(rs,ps,null);} return list; } }
service层:
接口:
public interface ShopService { public List<Shop> showShops(); }
实现:
public class ShopServiceImpl implements ShopService{ ShopDao dao=new ShopDaoImpl(); @Override public List<Shop> showShops() { List<Shop> list=new ArrayList<Shop>(); Connection con=null; try{ con= JDBCUtil.getcon(); con.setAutoCommit(false); list=dao.queryAllShop(con); System.out.println("-----查询成功!-----"); con.commit(); }catch(Exception e){e.printStackTrace(); if(con!=null) try {con.rollback();} catch (SQLException ex) {ex.printStackTrace();}} return list; } }
实体类:
public class Shop { private Integer sid; private String sname; private Double price; private String intro; public Integer getSid() { return sid; } public void setSid(Integer sid) { this.sid = sid; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } public String getIntro() { return intro; } public void setIntro(String intro) { this.intro = intro; } @Override public String toString() { return "商品信息:" + "商品编号:" + sid + ", 商品名称:" + sname + '\'' + ", 商品价格:" + price + ", 商品说明:" + intro ; } }
测试类:
public class TestMain{ private static ShopService ss=new ShopServiceImpl(); public static void main(String[] args) { showShops(); } public static void showShops(){ List<Shop> list=new ArrayList<Shop>(); list=ss.showShops(); } }