Guest User

Untitled

a guest
Dec 31st, 2017
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.21 KB | None | 0 0
  1. package com.ruszkowski89.RESTfulJerseyMessenger.database;
  2.  
  3. import jdk.nashorn.internal.objects.annotations.Where;
  4.  
  5. import java.sql.*;
  6. import java.util.Scanner;
  7.  
  8.  
  9. public class Database {
  10. public static void main(String args[]) {
  11.  
  12. String dbUrl = "jdbc:mysql://localhost:3306/demo"
  13. + "?useSSL=false&autoReconnect=true&useLegacyDatetimeCode=false&serverTimezone=CET";
  14. String user = "root";
  15. String password = "babajaga4";
  16.  
  17. String selectAllQuery = "SELECT * FROM employees";
  18. Connection connection = null;
  19. Statement statement = null;
  20.  
  21. try {
  22. connection =
  23. DriverManager.getConnection(dbUrl, user, password);
  24. connection.setAutoCommit(false);
  25.  
  26. // to show salaries before update
  27. statement = connection.createStatement();
  28. ResultSet resultSet = statement.executeQuery(selectAllQuery);
  29. System.out.println("Salaries before update: ");
  30. showSalaries(resultSet);
  31.  
  32. // to create transaction that raises engineers salaries by 10k
  33. CallableStatement callableStatement =
  34. connection.prepareCall("{call raise_engineers_salaries(?)}");
  35. callableStatement.setInt(1, 10000);
  36. callableStatement.execute();
  37.  
  38. // to show salaries after update and ask user if he wants to save result
  39. System.out.println("\nSalaries after update: ");
  40. resultSet = callableStatement.executeQuery(selectAllQuery);
  41. showSalaries(resultSet);
  42.  
  43. boolean askUser = askUserIfHeWantsToSave();
  44. if(askUser){
  45. connection.commit();
  46. }
  47. else
  48. connection.rollback();
  49.  
  50.  
  51.  
  52. } catch (SQLException e) {
  53. e.printStackTrace();
  54. }
  55. }
  56.  
  57. public static boolean askUserIfHeWantsToSave() throws SQLException {
  58. System.out.println("Are you sure you want to save new salaries? Type y/n and press enter.");
  59. Scanner scanner = new Scanner(System.in);
  60. String choice = scanner.next();
  61.  
  62. if (choice.equals("y")) {
  63. System.out.println("Y chosen");
  64. return true;
  65. }
  66. return false;
  67. }
  68.  
  69. public static void showSalaries(ResultSet resultSet) throws SQLException{
  70. while (resultSet.next()) {
  71. System.out.println(
  72. resultSet.getString("last_name") + " "
  73. + resultSet.getInt("salary"));
  74. }
  75. }
  76. }
Add Comment
Please, Sign In to add comment