Files
BUT2/DEV/DEV3.1/TP01/Exercise1/Database.java

68 lines
2.2 KiB
Java
Raw Normal View History

2025-09-26 08:56:23 +02:00
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
2025-09-26 13:21:58 +02:00
import java.util.ArrayList;
2025-09-26 08:56:23 +02:00
public class Database {
private Connection connection;
public Database() {
try {
Class.forName("org.mariadb.jdbc.Driver");
this.connection = DriverManager.getConnection(
"jdbc:mariadb://dwarves.iut-fbleau.fr/baudrier",
"baudrier",
"baudrier"
);
} catch(ClassNotFoundException exception) {
System.err.println("Class 'org.mariadb.jdbc.Driver' not found.");
} catch(SQLException exception) {
System.err.println("Error while trying to connect to the database");
}
}
2025-09-26 13:21:58 +02:00
public Votes getVotesFromCompetitor(String country) {
2025-09-26 08:56:23 +02:00
try {
PreparedStatement query = this.connection.prepareStatement(
2025-10-02 10:47:14 +02:00
"SELECT Voters.name, Votes.points " +
"FROM Votes " +
"JOIN Countries AS Competitors ON Votes.competitor_id = Competitors.id " +
"JOIN Countries AS Voters ON Votes.voter_id = Voters.id " +
"WHERE Competitors.name = ?;"
2025-09-26 08:56:23 +02:00
);
2025-10-02 10:47:14 +02:00
query.setString(1, country);
2025-09-26 08:56:23 +02:00
ResultSet result = query.executeQuery();
2025-09-26 13:21:58 +02:00
ArrayList<Vote> voteList = new ArrayList<>();
while(result.next()) {
voteList.add(new Vote(result.getString("name"), result.getInt("points")));
}
2025-09-26 08:56:23 +02:00
try {
query.close();
} catch(SQLException exception) {
System.err.println("Error while trying to close the query.");
}
2025-09-26 13:21:58 +02:00
return new Votes(country, voteList);
2025-09-26 08:56:23 +02:00
} catch(SQLException exception) {
2025-10-02 10:47:14 +02:00
System.err.println("Error while trying to prepare or execute the query (" + exception.getMessage() + ").");
2025-09-26 08:56:23 +02:00
}
return null;
}
public void close() {
try {
this.connection.close();
} catch(SQLException exception) {
System.err.println("Error while trying to close the connection.");
}
}
}