Advertisement
Guest User

Untitled

a guest
Mar 15th, 2016
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.05 KB | None | 0 0
  1. package be.pxl.JDBC;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.DriverManager;
  5. import java.sql.PreparedStatement;
  6. import java.sql.ResultSet;
  7. import java.sql.SQLException;
  8. public class BankTransfer {
  9.    private static final String QUERY =
  10.                 "select * from Accounts where number = ?";
  11.    private static final String UPDATE =
  12.                 "update Accounts set amount = ? where number = ?";
  13.    public static void main(String[] args) throws Exception {
  14.       try (Connection con = DriverManager.getConnection(
  15.                               "jdbc:mysql://noelvaes.eu/StudentDB",
  16.                               "student","student123");) {
  17.          con.setAutoCommit(false);
  18.          con.setTransactionIsolation(
  19.                            Connection.TRANSACTION_REPEATABLE_READ);
  20.          try (PreparedStatement qstmt = con.prepareStatement(QUERY);
  21.                  PreparedStatement ustmt = con.prepareStatement(UPDATE);){
  22.              setAmount(ustmt, 1, 100);
  23.              setAmount(ustmt, 2, 0);
  24.              double amount1 = 0;
  25.              double amount2 = 0;
  26.  
  27.              while ((amount1 = getAmount(qstmt, 1)) > 0) {//tx start amount2 = getAmount(qstmt, 2);
  28.                     setAmount(ustmt, 1, amount1 -= 1);
  29.                     setAmount(ustmt, 2, amount2 += 1); System.out.println(amount1 + "\t" + amount2);
  30.                     con.commit();
  31.              }
  32.          } catch (Exception e) {
  33.              System.out.println(e.getMessage());
  34.              con.rollback();
  35.          }
  36.       }
  37.    }
  38.    public static void setAmount(PreparedStatement ustmt,
  39.                                 int number, double amount)
  40.          throws SQLException {
  41.       ustmt.setInt(2, number);
  42.       ustmt.setDouble(1, amount);
  43.       ustmt.executeUpdate();
  44.    }
  45.    
  46.    public static double getAmount(PreparedStatement qstmt,
  47.                                   int number) throws SQLException {
  48.       double amount = 0;
  49.       qstmt.setInt(1, number);
  50.       try (ResultSet rs = qstmt.executeQuery()) {
  51.          if (rs.next()) {
  52.             amount = rs.getDouble("amount");
  53.          }
  54.       }
  55.       return amount;
  56.    }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement