Advertisement
Guest User

Untitled

a guest
Feb 26th, 2019
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.85 KB | None | 0 0
  1.  
  2. package basicJDBCExample;
  3.  
  4. import java.util.Scanner;
  5. import java.sql.*;
  6.  
  7. public class Main {
  8.  
  9. public static void main(String[] args) {
  10. Scanner scan = new Scanner(System.in);
  11.  
  12. //loadDriver(); //Obsolete - only needed in rare cases.
  13. //try with resources (Java 7) - automatically calls connection.close() on end of try-catch block
  14. //Ensures that connections aren't left hanging
  15. try (Connection connection = DriverManager.getConnection("jdbc:mysql://ec2-52-30-211-3.eu-west-1.compute.amazonaws.com/s175124"
  16. , "s175124", "HMdWGDg3RRUx7sKh4rS3b")){
  17. Statement statement = connection.createStatement();
  18. Statement statement1 = connection.createStatement();
  19. System.out.println("Insert ID");
  20. int id = scan.nextInt();
  21. System.out.println("Insert indhold");
  22. Scanner scan1 = new Scanner(System.in);
  23. String indhold = scan1.nextLine();
  24. statement1.executeUpdate("INSERT INTO test VALUES ("+id+", \""+indhold+"\")");
  25. ResultSet resultSet = statement.executeQuery("SELECT * FROM test");
  26. System.out.println("Got resultset from database:");
  27. while (resultSet.next()){
  28. System.out.println(resultSet.getString(1) + ": " + resultSet.getString(2));
  29. }
  30. } catch (SQLException e) {
  31. //Remember to handle Exceptions gracefully! Connection might be Lost....
  32. e.printStackTrace();
  33. }
  34.  
  35. }
  36.  
  37. /**
  38. * Old School and should be obsolete - Use only if there is a complaint about the driver missing...
  39. */
  40. @Deprecated
  41. private static void loadDriver() {
  42.  
  43. try {
  44. Class.forName("com.mysql.cj.Driver");
  45. } catch (ClassNotFoundException e) {
  46. e.printStackTrace();
  47. }
  48. }
  49.  
  50.  
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement