1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
|
public void transfert(Connexion conn, String emt, String dest, int montant) {
String emt = jTnumem.getText();
String dest= jTnumde.getText();
int montant = Integer.parseInt(jTwari.getText());
try {
startTransaction(conn);
transfert(conn, emt, dest, montant);
}
catch(SQLException e) {
e.printStackTrace();
try {
rollbackTransaction(conn);
}
catch(SQLException se) {
se.printStackTrace();
}
JOptionPane.showMessageDialog(null, "Une erreur de base de données à eu lieu : transfert annulé", "Erreur", JOptionPane.ERROR_MESSAGE );
}
finally {
endTransaction(conn);
}
}
public void transfert(Connexion conn, String emt, String dest, int montant) throws SQLException {
if ( compteExiste(conn, emt) ) {
if ( compteExiste(conn, dest) ) {
if ( debiter( conn, emt, montant ) {
crediter( conn, dest, montant );
commitTransaction(conn);
JOptionPane.showMessageDialog(null, "transfert effectué");
}
else {
JOptionPane.showMessageDialog(null, "solde du compte emetteur inferieur au débit demandé (transfert impossible)");
}
}
else {
JOptionPane.showMessageDialog(null, "compte destinataire inexistant");
}
}
else {
JOptionPane.showMessageDialog(null, "compte emetteur inexistant");
}
}
public boolean compteExiste(Connection conn, String id) throws SQLException {
String gninili = "SELECT solde FROM comptes WHERE numCompte=?";
try(PreparedStatement ps= conn.prepareStatement(gninili)) {
ps.setString(1, id);
ResultSet rs= ps.executeQuery();
return rs.next();
}
return false;
}
public boolean debiterCompte(Connection conn, String id, int montant) throws SQLException {
String agnini = "UPDATE comptes SET solde= solde - ? WHERE NumCompte = ? AND solde>= ?";
try(PreparedStatement cisse = conn.prepareStatement(agnini)) {
cisse.setInt(1, montant);
cisse.setString(2,id);
cisse.setInt(3, montant);
return cisse.executeUpdate()==1;
}
}
public boolean crediterCompte(Connection conn, String id, int montant) throws SQLException {
String agnini = "UPDATE comptes SET solde= solde + ? WHERE NumCompte = ?";
try(PreparedStatement cisse = conn.prepareStatement(agnini)) {
cisse.setInt(1, montant);
cisse.setString(2,id);
return cisse.executeUpdate()==1;
}
}
// gestion simplifiée de la transaction (voir les savePoint pour une vraie gestion)
public void startTransaction(Connection conn) {
conn.setAutoCommit(false);
}
public void endTransaction(Connection conn) {
conn.setAutoCommit(true);
}
public void commitTransaction(Connection conn) throws SQLException {
conn.commit();
}
public void rollbackTransaction(Connection conn) throws SQLException {
conn.rollback();
} |
Partager