-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Data access class that gets all the distinct/unique categories from the database.
- Loading branch information
Showing
1 changed file
with
53 additions
and
0 deletions.
There are no files selected for viewing
53 changes: 53 additions & 0 deletions
53
...application/src/main/java/ntnu/systemutvikling/team6/database/Readers/CategorySelect.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | ||
| } | ||
| } |