Advertisement
Guest User

Untitled

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