creation de la base de donne et l'affichage des score

This commit is contained in:
llample3
2026-02-19 20:21:47 +01:00
parent a32c41f369
commit 6b22b8530d
5 changed files with 140 additions and 2 deletions

View File

@@ -0,0 +1,96 @@
package linea;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class GestionBDD {
private static final String URL = "jdbc:sqlite:score.db";
//connexion bdd
private static Connection connecter() throws SQLException {
return DriverManager.getConnection(URL);
}
//creation de la table score a ca premiere execution
public static void creerTableSiAbsente() {
String sql = """
CREATE TABLE IF NOT EXISTS scores (
id INTEGER PRIMARY KEY AUTOINCREMENT,
score INTEGER NOT NULL,
date TEXT NOT NULL
);
""";
try (Connection connexion = connecter();
Statement statement = connexion.createStatement()) {
statement.execute(sql);
} catch (SQLException e) {
e.printStackTrace();
}
}
// Ajouter un score a la fin de la partie
public static void ajouterScore(int score) {
String sql = "INSERT INTO scores(score, date) VALUES(?, ?)";
try (Connection connexion = connecter();
PreparedStatement requete = connexion.prepareStatement(sql)) {
requete.setInt(1, score);
requete.setString(2, java.time.LocalDate.now().toString());
requete.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
// Récupérer tous les scores
public static List<Integer> recupererTousLesScores() {
List<Integer> listeScores = new ArrayList<>();
String sql = "SELECT score FROM scores ORDER BY date DESC";
try (Connection connexion = connecter();
Statement statement = connexion.createStatement();
ResultSet resultat = statement.executeQuery(sql)) {
while (resultat.next()) {
listeScores.add(resultat.getInt("score"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return listeScores;
}
// Récupérer le meilleur score
public static int recupererMeilleurScore() {
String sql = "SELECT MAX(score) AS meilleur FROM scores";
try (Connection connexion = connecter();
Statement statement = connexion.createStatement();
ResultSet resultat = statement.executeQuery(sql)) {
if (resultat.next()) {
return resultat.getInt("meilleur");
}
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
}