Ejemplo n.º 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;
  }
Ejemplo n.º 2
0
  @Override
  public boolean add(News news) throws AppException {
    Map<String, Object> session = ActionContext.getContext().getSession();
    Integer userId = (Integer) session.get("userId");

    boolean flag = false;
    Connection conn = null;
    PreparedStatement psmt = null;
    ResultSet rs = null;
    String sql =
        "insert into t_news"
            + "(title,user_id,newsType_id,source,author,createTime,keywords,content)"
            + "values(?,?,?,?,?,?,?,?)";
    // 预编译sql,并指定返回生成的主键
    try {
      conn = DBUtil.getConnection();
      psmt = conn.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
      // 设置参数值
      psmt.setString(1, news.getTitle());
      psmt.setInt(2, userId);
      psmt.setInt(3, news.getNewsType_id());
      psmt.setString(4, news.getSource());
      psmt.setString(5, news.getAuthor());
      psmt.setString(6, news.getCreateTime());
      psmt.setString(7, news.getKeywords());
      psmt.setString(8, news.getContent());

      psmt.executeUpdate(); // 执行更新操作
      rs = psmt.getGeneratedKeys(); // 得到插入行的主键,结果集中只有一条记录
      if (rs.next()) {
        news.setId(rs.getInt(1)); // 获取主键的值,并设置到news对象中
        flag = true; // 如果受影响行数大于0,操作成功
      }
    } catch (SQLException e) {
      e.printStackTrace();
      throw new AppException("com.xiongyu.dao.impl.NewsDaoImpl.add");
    } finally {
      // 关闭数据库操作对象,释放资源
      DBUtil.closeResultSet(rs);
      DBUtil.closePreparedStatement(psmt);
      DBUtil.closeConnection(conn);
    }
    return flag;
  }