Beispiel #1
0
  @Override
  public News getById(int id) throws AppException {
    News news = null;
    // 声明数据库连接对象,预编译对象的结果集对象
    Connection conn = null;
    PreparedStatement psmt = null;
    ResultSet rs = null;
    try {
      // 创建数据库连接
      conn = DBUtil.getConnection();
      String sql =
          "select id,author,title,createTime,source,click,content "
              + "from t_news where id=? and del=0";
      // 设置从参数,进行查询
      // 预编译sql,并设置参数
      psmt = conn.prepareStatement(sql);
      psmt.setInt(1, id); // 设置新闻id
      // 执行查询
      rs = psmt.executeQuery(); // 执行查询操作
      // 提取信息,保存到newsList中
      if (rs.next()) {
        news = new News(); // 创建一个News实例对象
        // 设置news对象的各属性的值
        news.setId(rs.getInt("id"));
        news.setAuthor(rs.getString("author"));
        news.setTitle(rs.getString("title"));
        news.setCreateTime(rs.getString("createTime"));
        news.setSource(rs.getString("source"));
        int click = rs.getInt("click") + 1;
        news.setClick(click);
        news.setContent(rs.getString("content"));

        updateClick(id, click);
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      // 关闭数据库操作对象,释放资源
      DBUtil.closeResultSet(rs);
      DBUtil.closePreparedStatement(psmt);
      DBUtil.closeConnection(conn);
    }
    return news;
  }