Beispiel #1
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;
  }