BUT2/DEV/DEV_Madelaine/Shadock_couliior/DonjonBD.java

98 lines
3.0 KiB
Java

import org.mariadb.jdbc.*;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class DonjonBD implements Donjon {
private int idPiece;
private int contenu;
private Connection connexion;
public DonjonBD(){
try{
this.ouvrirConnexion();
PreparedStatement requete = this.connexion.prepareStatement(
"SELECT idPiece,contenu FROM Piece");
ResultSet resultat = requete.executeQuery();
requete.close();
if (resultat.next()){
this.idPiece = resultat.getInt("idPiece");
this.contenu = resultat.getInt("contenu");
}
resultat.close();
}
catch(SQLException e){
System.out.println(e);
this.fermerConnexion();
}
}
@Override
public Piece apres(){
try{
PreparedStatement requete = this.connexion.prepareStatement(
"SELECT idPiece,contenu FROM Piece WHERE idPiece=(Select apres FROM Piece WHERE idPiece=?)");
requete.setInt(1, this.idPiece);
ResultSet resultat = requete.executeQuery();
requete.close();
if (resultat.next()){
this.idPiece = resultat.getInt("idPiece");
this.contenu = resultat.getInt("contenu");
}
resultat.close();
return new PieceConcrete(this.contenu);
}
catch(SQLException e){
return null;
}
}
@Override
public Piece avant(){
try{
PreparedStatement requete = this.connexion.prepareStatement(
"SELECT idPiece,contenu FROM Piece WHERE apres=?");
requete.setInt(1, this.idPiece);
ResultSet resultat = requete.executeQuery();
requete.close();
if (resultat.next()){
this.idPiece = resultat.getInt("idPiece");
this.contenu = resultat.getInt("contenu");
}
resultat.close();
return new PieceConcrete(this.contenu);
}
catch(SQLException e){
return null;
}
}
@Override
public Piece ici() {
return new PieceConcrete(this.contenu);
}
public void fermerConnexion(){
try {
this.connexion.close();
} catch (SQLException e) {
}
}
public void ouvrirConnexion() throws SQLException {
try {
try {
Class.forName("org.mariadb.jdbc.Driver");
} catch (ClassNotFoundException e) {
throw new RuntimeException("ClassNotFoundException", e);
}
this.connexion = DriverManager.getConnection(
"jdbc:mariadb://dwarves.iut-fbleau.fr/williatt",
"williatt", "OscarSQL92");
} catch (SQLException e) {
throw new SQLException("Connexion au serveur impossible ! Verifiez votre connexion internet puis reessayez",
e);
}
}
}