Advertisement
Guest User

Untitled

a guest
Mar 16th, 2016
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.94 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 =
  19. PreparedStatement ustmt =
  20. setAmount(ustmt, 1, 100);
  21. setAmount(ustmt, 2, 0);
  22. double amount1 = 0;
  23. double amount2 = 0;
  24. con.prepareStatement(QUERY);
  25. con.prepareStatement(UPDATE);) {
  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. public static void setAmount(PreparedStatement ustmt,
  38. //tx end
  39. int number, double amount)
  40. throws SQLException {
  41. ustmt.setInt(2, number);
  42. ustmt.setDouble(1, amount);
  43. ustmt.executeUpdate();
  44. }
  45. public static double getAmount(PreparedStatement qstmt,
  46. int number) throws SQLException {
  47. double amount = 0;
  48. qstmt.setInt(1, number);
  49. try (ResultSet rs = qstmt.executeQuery()) {
  50. if (rs.next()) {
  51. amount = rs.getDouble("amount");
  52. }
  53. }
  54. return amount;
  55. }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement