Files
BUT2/DEV/DEV3.1/TP01/Exercise1/Database.java
2025-09-26 13:21:58 +02:00

65 lines
2.0 KiB
Java

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
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");
}
}
public Votes getVotesFromCompetitor(String country) {
try {
PreparedStatement query = this.connection.prepareStatement(
"SELECT Countries.name Votes.points" +
"FROM Votes JOIN Countries ON Votes.competitor_id = Countries.id" +
"WHERE Countries.name = " + country
);
ResultSet result = query.executeQuery();
ArrayList<Vote> voteList = new ArrayList<>();
while(result.next()) {
voteList.add(new Vote(result.getString("name"), result.getInt("points")));
}
try {
query.close();
} catch(SQLException exception) {
System.err.println("Error while trying to close the query.");
}
return new Votes(country, voteList);
} catch(SQLException exception) {
System.err.println("Error while trying to prepare or execute the query.");
}
return null;
}
public void close() {
try {
this.connection.close();
} catch(SQLException exception) {
System.err.println("Error while trying to close the connection.");
}
}
}