diff --git a/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/database/Readers/CategorySelect.java b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/database/Readers/CategorySelect.java new file mode 100644 index 0000000..5ce735e --- /dev/null +++ b/helpmehelpapplication/src/main/java/ntnu/systemutvikling/team6/database/Readers/CategorySelect.java @@ -0,0 +1,53 @@ +package ntnu.systemutvikling.team6.database.Readers; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import ntnu.systemutvikling.team6.database.DatabaseConnection; + +/** + * Data access class responsible for getting all the distinct categories from the database. + * + *

All queries are executed against a MySQL database via a {@link DatabaseConnection}. + */ +public class CategorySelect { + private final DatabaseConnection connection; + + /** + *Constructs a new {@code CharitySelect} with the given database connection. + * + * @param connection the {@link DatabaseConnection} to use for executing queries; must not be + * {@code null} + */ + public CategorySelect(DatabaseConnection connection) { + this.connection = connection; + } + + /** + * Retrieves all the categories listed in the Category table of the database. + * + * @return a list of strings containing the name of the categories + */ + public List getCategoriesFromDB() { + List categories = new ArrayList<>(); + + try (Connection conn = connection.getMySqlConnection(); + Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT category FROM Categories")) { + + while (rs.next()) { + categories.add(rs.getString("category")); + } + + } catch (SQLException e) { + e.printStackTrace(); + throw new RuntimeException( + "ERROR: Something went wrong during fetching categories from database."); + } + + return categories; + } +}