Advertisement
Guest User

Untitled

a guest
Apr 28th, 2019
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.60 KB | None | 0 0
  1. import java.util.Map;
  2. import java.util.HashMap;
  3. import java.sql.ResultSet;
  4. import java.sql.Statement;
  5. import java.sql.Connection;
  6. import java.util.ArrayList;
  7. import java.sql.SQLException;
  8. import java.sql.DriverManager;
  9.  
  10. public class Database {
  11. public static void main(String[] args) throws ClassNotFoundException, SQLException {
  12. Class.forName("com.mysql.cj.jdbc.Driver");
  13. System.out.println("Driver loaded.");
  14.  
  15. ArrayList<String> options = new ArrayList<>();
  16. options.add("serverTimezone=UTC");
  17.  
  18. Connection connection = DriverManager.getConnection("jdbc:mysql://" + config("host") + ":" + config("port") + "/" + config("name") + "?" + String.join("&", options), config("user"), config("pass"));
  19. System.out.println("Connection succeeded.");
  20.  
  21. //
  22.  
  23. Statement statement = connection.createStatement();
  24.  
  25. ArrayList<String> queries = new ArrayList<>();
  26. queries.add("SELECT id, name FROM users");
  27.  
  28. ResultSet r = statement.executeQuery(queries.get(0));
  29.  
  30. /**
  31. * Displaying the records.
  32. */
  33. while (true) {
  34. if (!r.next()) {
  35. break;
  36. }
  37.  
  38. System.out.println(r.getString(1) + "\t" + r.getString(2));
  39. }
  40. }
  41.  
  42. public static String config(String key) {
  43. Map<String, String> config = new HashMap<>();
  44. config.put("host", "localhost");
  45. config.put("port", "8889");
  46. config.put("name", "database");
  47. config.put("user", "root");
  48. config.put("pass", "root");
  49.  
  50. return config.containsKey(key) ? config.get(key) : null;
  51. }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement