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

66 lines
2.0 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;
public class Database {
//Countries
public static String COUNTRY_ID = "id";
public static String COUNTRY_NAME = "name";
//Votes table
public static String VOTES_COMPETITOR_ID = "competitor_id";
public static String VOTES_VOTER_ID = "voter_id";
public static String VOTES_POINTS = "points";
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 ResultSet getVotesFromCompetitor(String country) {
try {
PreparedStatement query = this.connection.prepareStatement(
"SELECT Countries.name, Countries.points FROM Votes INNER JOIN Countries ON Votes.competitor_id = Countries.id WHERE Votes.competitor_id = Countries.id"
);
ResultSet result = query.executeQuery();
try {
query.close();
} catch(SQLException exception) {
System.err.println("Error while trying to close the query.");
}
return result;
} 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.");
}
}
}