コード例 #1
0
  @Override
  public News getNewsById(int id) {
    News news = new News();
    SqlUtilities.jbdcUtil();
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;

    try {
      connection =
          DriverManager.getConnection(
              "jdbc:mysql://localhost:3306/fourscorepicks", "fourscorepicks", "fourscorepicks");

      preparedStatement = connection.prepareStatement("SELECT * FROM news WHERE id=?");
      preparedStatement.setInt(1, id);
      resultSet = preparedStatement.executeQuery();

      resultSet.next();
      news.setDatePosted(resultSet.getTimestamp("date_posted"));
      news.setNewsText(resultSet.getString("news"));
      news.setId(resultSet.getInt("id"));

    } catch (SQLException e) {
      throw new RuntimeException(e);
    } finally {
      SqlUtilities.closePreparedStatement(preparedStatement);
      SqlUtilities.closeResultSet(resultSet);
      SqlUtilities.closeConnection(connection);
    }

    return news;
  }
コード例 #2
0
  @Override
  public List<News> getNewsList() {
    List<News> newsList = new ArrayList<News>();
    SqlUtilities.jbdcUtil();
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;

    try {
      connection =
          DriverManager.getConnection(
              "jdbc:mysql://localhost:3306/fourscorepicks", "fourscorepicks", "fourscorepicks");

      preparedStatement =
          connection.prepareStatement("SELECT * FROM news ORDER BY date_posted DESC");

      resultSet = preparedStatement.executeQuery();

      while (resultSet.next()) {
        News news = new News();
        news.setDatePosted(resultSet.getTimestamp("date_posted"));
        news.setNewsText(resultSet.getString("news"));
        news.setId(resultSet.getInt("id"));
        newsList.add(news);
      }

    } catch (SQLException e) {
      throw new RuntimeException(e);
    } finally {
      SqlUtilities.closePreparedStatement(preparedStatement);
      SqlUtilities.closeResultSet(resultSet);
      SqlUtilities.closeConnection(connection);
    }

    return newsList;
  }