Beispiel #1
0
  @Override
  public DeptVO findByPrimaryKey(Integer deptno) {

    DeptVO deptVO = null;
    Connection con = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;

    try {

      Class.forName(driver);
      con = DriverManager.getConnection(url, userid, passwd);
      pstmt = con.prepareStatement(GET_ONE_STMT);

      pstmt.setInt(1, deptno);

      rs = pstmt.executeQuery();

      while (rs.next()) {
        // deptVO 也稱為 Domain objects
        deptVO = new DeptVO();
        deptVO.setDeptno(rs.getInt("deptno"));
        deptVO.setDname(rs.getString("dname"));
        deptVO.setLoc(rs.getString("loc"));
      }

      // Handle any driver errors
    } catch (ClassNotFoundException e) {
      throw new RuntimeException("Couldn't load database driver. " + e.getMessage());
      // Handle any SQL errors
    } catch (SQLException se) {
      throw new RuntimeException("A database error occured. " + se.getMessage());
      // Clean up JDBC resources
    } finally {
      if (rs != null) {
        try {
          rs.close();
        } catch (SQLException se) {
          se.printStackTrace(System.err);
        }
      }
      if (pstmt != null) {
        try {
          pstmt.close();
        } catch (SQLException se) {
          se.printStackTrace(System.err);
        }
      }
      if (con != null) {
        try {
          con.close();
        } catch (Exception e) {
          e.printStackTrace(System.err);
        }
      }
    }
    return deptVO;
  }
Beispiel #2
0
  @Override
  public List<DeptVO> getAll() {
    List<DeptVO> list = new ArrayList<DeptVO>();
    DeptVO deptVO = null;

    Connection con = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;

    try {

      Class.forName(driver);
      con = DriverManager.getConnection(url, userid, passwd);
      pstmt = con.prepareStatement(GET_ALL_STMT);
      rs = pstmt.executeQuery();

      while (rs.next()) {
        deptVO = new DeptVO();
        deptVO.setDeptno(rs.getInt("deptno"));
        deptVO.setDname(rs.getString("dname"));
        deptVO.setLoc(rs.getString("loc"));
        list.add(deptVO); // Store the row in the list
      }

      // Handle any driver errors
    } catch (ClassNotFoundException e) {
      throw new RuntimeException("Couldn't load database driver. " + e.getMessage());
      // Handle any SQL errors
    } catch (SQLException se) {
      throw new RuntimeException("A database error occured. " + se.getMessage());
    } finally {
      if (rs != null) {
        try {
          rs.close();
        } catch (SQLException se) {
          se.printStackTrace(System.err);
        }
      }
      if (pstmt != null) {
        try {
          pstmt.close();
        } catch (SQLException se) {
          se.printStackTrace(System.err);
        }
      }
      if (con != null) {
        try {
          con.close();
        } catch (Exception e) {
          e.printStackTrace(System.err);
        }
      }
    }
    return list;
  }