BBS.Model&&Service

一、Model层

  建立一个category class ,设置category 属性、get&&set方法

二、Service层

  DB.java部分代码:

 1     public static Connection createConn() {
 2         Connection conn = null;
 3         try {
 4             Class.forName("com.mysql.jdbc.Driver");
 5             conn = DriverManager.getConnection("jdbc:mysql://localhost/bbs2009", "root", "bjsxt");
 6         } catch (ClassNotFoundException e) {
 7             e.printStackTrace();
 8         } catch (SQLException e) {
 9             e.printStackTrace();
10         }
11         return conn;
12     }
13     
14     public static PreparedStatement prepare(Connection conn, String sql) {
15         PreparedStatement ps = null;
16         try {
17             ps = conn.prepareStatement(sql);
18         } catch (SQLException e) {
19             e.printStackTrace();
20         }
21         return ps;
22     }
23

  CategoryService.java部分代码

 1 public class CategoryService {
 2     public void add(Category c) {
 3         Connection conn = DB.createConn();
 4         String sql = "insert into _category values (null, ?, ?)";
 5         PreparedStatement ps = DB.prepare(conn, sql);
 6         try {
 7             ps.setString(1, c.getName());
 8             ps.setString(2, c.getDescription());
 9             ps.executeUpdate();
10         } catch (SQLException e) {
11             e.printStackTrace();
12         }
13         DB.close(ps);
14         DB.close(conn);
15     }
16     
17     public List<Category> list() {
18         Connection conn = DB.createConn();
19         String sql = "select * from _category";
20         PreparedStatement ps = DB.prepare(conn, sql);
21         List<Category> categories = new ArrayList<Category>();
22         try {
23             ResultSet rs = ps.executeQuery();
24             Category c = null;
25             while(rs.next()) {
26                 c = new Category();
27                 c.setName(rs.getString("name"));
28                 c.setDescription(rs.getString("description"));
29                 categories.add(c);
30             }
31         } catch (SQLException e) {
32             e.printStackTrace();
33         }
34         DB.close(ps);
35         DB.close(conn);
36         return categories;
37     }

 

posted @ 2013-03-14 00:05  hi_stefen  Views(200)  Comments(0)    收藏  举报