Advertisement
Guest User

Untitled

a guest
Mar 3rd, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.39 KB | None | 0 0
  1. import java.sql.*;
  2. import java.util.function.Function;
  3.  
  4. // TODO: documentation
  5. public class GigDataStore {
  6.  
  7.     private final String DB_URL;
  8.     private final String DB_USER;
  9.     private final String DB_PASS;
  10.  
  11.     public GigDataStore(String DB_URL, String DB_USER, String DB_PASS) {
  12.         this.DB_URL = DB_URL;
  13.         this.DB_USER = DB_USER;
  14.         this.DB_PASS = DB_PASS;
  15.     }
  16.  
  17.     public Gig getGig(int id) {
  18.         return runOnNewStatement(statement -> {
  19.             try {
  20.                 String query = String.format(
  21.                         "SELECT * FROM dm.gigs WHERE id = %d;",
  22.                         id
  23.                 );
  24.                 ResultSet rs = statement.executeQuery(query);
  25.             }
  26.         });
  27.     }
  28.  
  29.     // run whatever queries we need, and then close it
  30.     // I got tired of typing this all out
  31.     // Also, functional Java! Yay!
  32.     private <T> T runOnNewStatement(Function<Statement, T> dataFunction) {
  33.         // this syntax automatically closes everything if there is a problem
  34.         // don't you just love multiple-use syntax?
  35.         try (Connection conn = DriverManager.getConnection(this.DB_URL, this.DB_USER, this.DB_PASS);
  36.             Statement stmt = conn.createStatement()) {
  37.             return dataFunction.apply(stmt);
  38.         } catch (SQLException e) {
  39.             e.printStackTrace();
  40.         }
  41.         return null;
  42.     }
  43.  
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement