Skip to content

Commit

Permalink
Added CategorySelect
Browse files Browse the repository at this point in the history
Data access class that gets all the distinct/unique categories from the database.
  • Loading branch information
roaraf committed Apr 18, 2026
1 parent fa4a687 commit fda1312
Showing 1 changed file with 53 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -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.
*
* <p>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<String> getCategoriesFromDB() {
List<String> 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;
}
}

0 comments on commit fda1312

Please sign in to comment.